简体   繁体   中英

How to import default VPC into CloudFormation stack and recreate it with AWS CDK?

I want to create an AWS CloudFormation stack with all of my network resources. So I also want to include my default VPC. I created my stack with AWS CDK and want to configure all of my resources with CDK.

To import my default VPC I used the management console and the stack action "Import resources into stack". I used this template to import my default VPC:

Resources:
  VPC:
    Type: AWS::EC2::VPC
    DeletionPolicy: Retain
    Properties:
      CidrBlock: 172.31.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
      InstanceTenancy: default

The import wizard called for the VPC ID and I used my default VPC ID. After successful import I got a CloudFormation template of the stack with the same content as above.

Now I wanted to recreate my default VCP with AWS CDK. I don't want to use Vpc.fromLookup or fromVpcAttributes . I want to create a new VPC with AWS CDK which is my default VPC. So I wrote:

const vpc = new ec2.Vpc(this, 'VPC', {
  cidr: "172.31.0.0/16",
  enableDnsSupport: true,
  enableDnsHostnames: true,
  defaultInstanceTenancy: DefaultInstanceTenancy.DEFAULT
});

But when I call cdk diff it shows:

[-] AWS::EC2::VPC VPC orphan
[+] AWS::EC2::VPC VPC VPCXYZ12345

So it wants to create a new VPC and my imported default VPC is orphaned.

I also tried to override the logical ID. So it matches with the ID of my default VPC:

const cfnVpc = vpc.node.defaultChild as cdk.CfnResource;
cfnVpc.overrideLogicalId('vpc-abcd1234');

But the output of cdk diff is like above but now with the VPC ID of my default VPC.

Is it even possible to import the default VPC into a CloudFormation stack and recreate it with AWS CDK?

Though you are keeping the stack name same, the logical id of the vpc resource in imported cloudformation and the cdk generated cloudformation are different. VPC vs VPCXYZ12345.

This is the reason why cdk diff is showing deleting and recreation.

Here is what we can ideally do:

  • Delete your existing cloudformation
  • Create cloudformation cdk --no-version-reporting synth
  • Grab the template from cdk.out
  • Import this in cloudformation console, just like your regular template.

This process should help you import your existing vpc into cdk. Here is an similar answer for importing DynamoDB table in cdk.

You can't mark non-default VPC as default, and you can't yourself reconstruct a default VPC. From docs :

You cannot restore a previous default VPC that you deleted, and you cannot mark an existing nondefault VPC as a default VPC.

You have to use AWS Console, SDK or CLI dedicated call to create a default VPC:

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