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.