Create a New AWS Lambda in CDK Using Pre-Existing CloudFormation Resources

In my current software development project, we recently needed to add a new AWS Lambda that would touch an already-existing relational database service (RDS) instance. While this might sound pretty simple, a few things complicated the matter. For one, our RDS instance was inside a virtual private cloud (VPC). This meant we would also need to add the newly-created lambda to the same VPC. No problem, right?

Create a New AWS Lambda in CDK Using Pre-Existing CloudFormation Resources

Problem

Well, there was one more problem adding complexity in our case. All the already-existing AWS infrastructure was set up with AWS CloudFormation, and we had recently wrapped that with AWS’s cloud development kit (CDK). This allowed us to define our AWS resources in Typescript. This is where the real complexity comes in (or so I thought). We needed a way to reference those pre-existing AWS resources created with CloudFormation, now in CDK.

After doing lots of research with my coworker Kendra Haan, we found a simple solution I’d like to share!

Solution

Find the file where you are creating your CDK app and import `ec2`, `rds`, and `lambda` from your aws package like so:

import * as ec2 from "@aws-cdk/aws-ec2";
import * as lambda from "@aws-cdk/aws-lambda";
import * as rds from "@aws-cdk/aws-rds";

Then, the first resource you’ll need to grab from your cfnTemplate will be your VPC. We found that you can use `fromLookup` to get this resource like this:

`const vpc = ec2.Vpc.fromLookup(stack, "external-vpc", {
  vpcName: “your-vpc-name-here”,
});`

Now that you have your VPC defined, let’s grab the pre-existing rds security group to add your new lambda to using `fromLookupByName`:

`const rdsSecurityGroup = ec2.SecurityGroup.fromLookupByName(
  stack,
  "your-new-id",
  “your-existing-sg-name”,
  vpc
);`

Great! Now let’s create the new lambda security group inside of your VPC:

`const lambdaSG = new ec2.SecurityGroup(
  stack,
  “new-lambda”,
  {
    vpc,
    allowAllOutbound: true,
    description: "security group for new lambda",
  }
);`

Now that you have all your resources defined in CDK, all you have to do is add an ingress rule to your RDS security group:

`rdsSecurityGroup.addIngressRule(
  ec2.Peer.securityGroupId(lambdaSG.securityGroupId),
  ec2.Port.tcp(your-port-number-here)
);`

Create a New AWS Lambda in CDK Using Pre-Existing CloudFormation Resources

This is all you need to connect your new lambda to your RDS instance! I hope this saves you lots of time looking into this problem if you are experiencing it.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *