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
gefragt vor 4 Monaten387 Aufrufe
1 Antwort
0
Akzeptierte Antwort

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

Colin
beantwortet vor 4 Monaten

Du bist nicht angemeldet. Anmelden um eine Antwort zu veröffentlichen.

Eine gute Antwort beantwortet die Frage klar, gibt konstruktives Feedback und fördert die berufliche Weiterentwicklung des Fragenstellers.

Richtlinien für die Beantwortung von Fragen