I have an AWS CDK stack with a lambda function that needs to insert into an RDS database. When the stack is deployed, the lambda function cannot access the database and gives an error: getaddrinfo ENOTFOUND [RDS endpoint as defined by me]. After manually adding the VPC, subnets and Security group that the RDS database is in, the lambda function works correctly.
How do you define the VPC, Subnets and Security group in AWS CDK, preferably in TypeScript? In as far as there is documentation, I tried:
const vpc = ec2.Vpc.fromLookup(this, "VPC", { vpcName: "myVPC" });
const securityGroup = ec2.SecurityGroup.fromSecurityGroupId(
this,
"SG",
"sg-XXXXX"
);
const subnet1a = ec2.PrivateSubnet.fromSubnetAttributes(this, "SUBNET1A", {
subnetId: "eu-central-1a"
});
const myLambda = new lambda.Function(this, "myLambda", {
runtime: lambda.Runtime.NODEJS_12_X,
code: lambda.Code.fromAsset("lambda"),
handler: "myLambda.handler",
description: "myLambda",
environment: {
DB_HOST: "XXXX",
DB_USER: "XXXX",
DB_PASSWORD: "XXXX",
DB_NAME: "XXXX"
},
vpc: vpc,
vpcSubnets: [subnet1a],
securityGroups: [securityGroup]
});
When running cdk deploy This gives an AWS CDK error: "Not possible to place Lambda Functions in a Public subnet Subprocess exited with error 1"
Any help is welcome.