简体   繁体   中英

How to import existing private subnets in a VPC in AWS CDK using TypeScript?

I have few private subnets in my VPC and i'm trying to import them using typescript as shown below:

    vpc1 = ec2.Vpc.fromLookup(this, 'myVpc',{isDefault: false, vpcId:vpcId });
   
   // Iterate the private subnets
    const selection = vpc1.selectSubnets({
      subnetType: ec2.SubnetType.PRIVATE
    });
   
   for (const subnet of selection.subnets) {

   }

I managed to import the VPC. But, the private subnets are not listed.

How can this be done?

When importing a vpc that is created outside CDK code to cdk, it will build a cdk.context.json file with vpc and subnet information and selectSubnets is merely extracting information from that vpc object that is built in that context file. Some documentation here .

vpc = ec2.Vpc.fromLookup(this, 'myVpc',{isDefault: false, vpcId:vpcId });

Subnet type is determined by CDK on multiple criteria

  1. Presence of tag aws-cdk:subnet-type which will be there if vpc is created by CDK itself.
  2. Based on presence of Internet Gateway (IGW), Nat Gateway or No Gateway. Ex: If there route to IGW, then it will be treated as PUBLIC.

We can observe what type cdk derived in cdk.context file.

在此处输入图像描述

If we don't like the subnet type by default or We need to specific subnets, cases where we have too many private subnets and we need import specefic one, we can always import them like this:

const subnet1 = ec2.Subnet.fromSubnetId(this, 'private-subnet-1', 'subnet-1234345');
const subnet2 = ec2.Subnet.fromSubnetId(this, 'private-subnet-2', 'subnet-456789');

With cdk v2 you can get the private subnets this way:

 vpc = ec2.Vpc.fromLookup(this, 'myVpc',{isDefault: false, vpcId:vpcId }); const privateSubnets: ec2.ISubnet[] = []; for (const subnet of vpc.privateSubnets) { privateSubnets.push(ec2.Subnet.fromSubnetAttributes(scope, subnet.subnetId, { subnetId: subnet.subnetId })); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM