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
preguntada hace 4 meses387 visualizaciones
1 Respuesta
0
Respuesta aceptada

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

Colin
respondido hace 4 meses

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas