Home > front end >  How can I add an already existing VPC to a lambda using AWS CDK?
How can I add an already existing VPC to a lambda using AWS CDK?

Time:01-24

Currently I'm using AWS CDK to create a simple lambda function.

const hello = new Function(this,"HelloHandler",{
      role:lambdaRole,
      runtime:Runtime.NODEJS_16_X,
      code:Code.fromAsset("dist"),
      handler:"index.handler",
    }) 

I wish to add a VPC to the lambda. Normally one would need to create a VPC in the normal manner. However in my scenario, I wish to add a VPC that already exists and was created using the AWS console.

Is there a way to do so?

Note:

  • I'm using TypeScript

CodePudding user response:

Using Vpc.fromLookup() method to import the VPC and then pass it as a parameter to the lambda.Function construct. Here's an example of how you can do this:

import * as cdk from 'aws-cdk-lib';
import * as lambda from '@aws-cdk/aws-lambda';
import * as ec2 from '@aws-cdk/aws-ec2';
    
const vpc = ec2.Vpc.fromLookup(this, "MyVPC", { vpcId: 'vpc-12345678' });
    
const myLambda = new lambda.Function(this, "MyLambda", {
        vpc: vpc,
        runtime: lambda.Runtime.NODEJS_12_X,
        handler: 'index.handler',
        code: lambda.Code.fromAsset('lambda-code-directory')
});

  • Related