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
질문됨 4달 전387회 조회
1개 답변
0
수락된 답변

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

Colin
답변함 4달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠