Lambda not connecting to Elasticache Serverless instance

0

I have difficulty accessing my CDK-created Elasticache Serverless instance from my lambda function. It times out while trying to connect. What am I doing wrong? Note that I tried adding a permission to the lambda. Here is my CDK code:

export class ElasticacheStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const elasticacheServerless = new elasticache.CfnServerlessCache(
      this,
      "elasticacheServerless",
      {
        engine: "redis",
        serverlessCacheName: "serverlessCache",
      }
    );

    const endpoint = elasticacheServerless.attrEndpointAddress;
    const port = elasticacheServerless.attrEndpointPort;

    const lambda = new nodejs.NodejsFunction(this, "redisHandler", {
      entry: "handlers/elasticache.ts",
      environment: { REDIS_URL: "redis://" + endpoint + ":" + port },
    });

    const policyStatement = new iam.PolicyStatement();
    policyStatement.addResources(
      elasticacheServerless.getAtt("ARN").toString()
    );
    policyStatement.addActions("elasticache:Connect");

    lambda.addToRolePolicy(policyStatement);
  }
}

and here is my lambda's code:

import { createClient } from "redis";

export const handler = async (event, context) => {
  const client = await createClient({
    url: process.env.REDIS_URL,
    socket: { tls: true },
  })
    .on("error", (e) => console.log("Redis error", e))
    .connect();
  await client.set("isSillyExample", "true");
  const value = await client.get("isSillyExample");
  await client.disconnect();
  return value;
};

I've also tried setting tls to false but that doesn't change anything. I also tried changing the connection prototcol to rediss:// (with two s) to imply a secure connection, but no luck.

Colin
asked 3 months ago337 views
1 Answer
0
Accepted Answer

I fixed it myself by adding the lambda to the default VPC in which the serverless Elasticache instance was runnning. Hurray!

Colin
answered 3 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions