36

Hi I am working on aws cdk. I am trying to get existing non-default vpc. I tried below options.

vpc = ec2.Vpc.from_lookup(self, id = "VPC", vpc_id='vpcid', vpc_name='vpc-dev')

This results in below error

[Error at /LocationCdkStack-cdkstack] Request has expired.
[Warning at /LocationCdkStack-cdkstack/TaskDef/mw-service] Proper policies need to be attached before pulling from ECR repository, or use 'fromEcrRepository'.
Found errors

Other method I tried is

vpc = ec2.Vpc.from_vpc_attributes(self, 'VPC', vpc_id='vpc-839227e7', availability_zones=['ap-southeast-2a','ap-southeast-2b','ap-southeast-2c'])

This results in

[Error at /LocationCdkStack-cdkstack] Request has expired.
[Warning at /LocationCdkStack-cdkstack/TaskDef/mw-service] Proper policies need to be attached before pulling from ECR repository, or use 'fromEcrRepository'.
Found errors

Other method I tried is

vpc = ec2.Vpc.from_lookup(self, id = "VPC", is_default=True) // This will get default vpc and this will work

Can someone help me to get non-default vpc in aws cdk? Any help would be appreciated. Thanks

Niranjan
  • 1,881
  • 6
  • 44
  • 71

3 Answers3

63

Take a look at aws_cdk.aws_ec2 documentation and at CDK Runtime Context.

If your VPC is created outside your CDK app, you can use Vpc.fromLookup(). The CDK CLI will search for the specified VPC in the the stack’s region and account, and import the subnet configuration. Looking up can be done by VPC ID, but more flexibly by searching for a specific tag on the VPC.

Usage:

# Example automatically generated. See https://github.com/aws/jsii/issues/826
from aws_cdk.core import App, Stack, Environment
from aws_cdk import aws_ec2 as ec2

# Information from environment is used to get context information
# so it has to be defined for the stack
stack = MyStack(
    app, "MyStack", env=Environment(account="account_id", region="region")
)

# Retrieve VPC information
vpc = ec2.Vpc.from_lookup(stack, "VPC",
    # This imports the default VPC but you can also
    # specify a 'vpcName' or 'tags'.
    is_default=True
)

Update with a relevant example:

vpc = ec2.Vpc.from_lookup(stack, "VPC",
    vpc_id = VPC_ID
)

Update with typescript example:

import ec2 = require('@aws-cdk/aws-ec2');
const getExistingVpc = ec2.Vpc.fromLookup(this, 'ImportVPC',{isDefault: true});

More info here.

Amit Baranes
  • 7,398
  • 2
  • 31
  • 53
  • Hi Thanks for your answer. VPC is created outside of cdk app and this is non-default vpc. from_lookup is used to get default vpc right? – Niranjan Dec 12 '19 at 10:05
  • Then just change `is_default` to False and provide the `vpcName` – Amit Baranes Dec 12 '19 at 10:06
  • vpc = ec2.Vpc.from_lookup(self, id = "VPC", vpc_name='vpc-dev' , is_default=False) this dint worked out for me. Yes my cdk is in python – Niranjan Dec 12 '19 at 10:06
  • Maybe this could be helpfull https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options – Amit Baranes Dec 12 '19 at 10:11
  • To make it work the environment needs to be properly defined for the stack with mandatory information `account` and `region`. – Romain Jun 22 '20 at 15:10
  • @Romain Share an example and I'll edit my answer according to it – Amit Baranes Jun 22 '20 at 15:38
  • 1
    @AmitBaranes just updated the answer with additional information. Feel free to review it. Hope it will help other people. – Romain Jun 23 '20 at 06:11
  • 1
    Please be aware that not setting isDefault is different from setting it false (or true for that matter). I can lookup my non-default VPC based on a name without errors, but the ID returned is a random one (not the right one). If I set isDefault to false, it gives me the correct one, and if I set it to true, it throws and error telling me that it is not my default VPC. – Michael Oct 07 '20 at 06:35
4

For AWS CDK v2 or v1(latest), You can use:

// You can either use vpcId OR vpcName and fetch the desired vpc
const getExistingVpc = ec2.Vpc.fromLookup(this, 'ImportVPC',{
      vpcId: "VPC_ID",
      vpcName: "VPC_NAME"
});
thoroc
  • 3,291
  • 2
  • 27
  • 34
-1

here is simple example

//get VPC Info form AWS account, FYI we are not rebuilding we are referencing 
const DefaultVpc = Vpc.fromVpcAttributes(this, 'vpcdev', {
    vpcId:'vpc-d0e0000b0',
    availabilityZones: core.Fn.getAzs(),
    privateSubnetIds: 'subnet-00a0de00',
    publicSubnetIds: 'subnet-00a0de00'
});
    
const yourService = new lambda.Function(this, 'SomeName', {
    code: lambda.Code.fromAsset("lambda"),
    handler: 'handlers.your_handler',
    role: lambdaExecutionRole,
    securityGroup: lambdaSecurityGroup,
    vpc: DefaultVpc,
    runtime: lambda.Runtime.PYTHON_3_7,
    timeout: Duration.minutes(2),
});
thoroc
  • 3,291
  • 2
  • 27
  • 34
grepit
  • 21,260
  • 6
  • 105
  • 81