简体   繁体   中英

How to check if a custom VPC already exist using AWS CDK?

I am doing a CDK script and to use the default VPC, I has this code:

vpc = ec2.Vpc.fromLookup(this, "UseDefaultVPC", {
  isDefault: true
});

To use a existing VPC (not default), I has this code (will search by existing tags):

vpc = ec2.Vpc.fromLookup(this, "UseCustomVPCAlreadyCreated", {
  tags: {
    environment: project.environment,
    project_name: project.name
  }
});

I need on the first time, that VPC be created, and on a update be reused. Something like this:

Try to use a existing vpc, if does not exist, create it

try {
  vpc = ec2.Vpc.fromLookup(this, "UseCustomVPCAlreadyCreated", {
    tags: {
      environment: project.environment,
      project_name: project.name,
    },
  });
  console.log("Using a custom VPC: ", vpc.vpcId);
} catch (error) {
  vpc = new ec2.Vpc(this, "CreateNewVPC", {
    cidr: "10.0.0.0/16",
    maxAzs: 99, // 99 to use all AZs
  });
  console.log("VPC does not exist, creating it: ", vpc.vpcId);
}

But my try catch does not work. And the output is:

It try two times and fail, don't go to catch:

$ cdk deploy --profile fagianijunior
Using a custom VPC:  vpc-12345
Using a custom VPC:  vpc-12345
[Error at /WordpressStack] Could not find any VPCs matching {"account":"NNNNNNNNNNNN","region":"us-east-1","filter":{"tag:environment":"staging","tag:project_name":"wordpress"},"returnAsymmetricSubnets":true}
Found errors

You don't have to check if the VPC exists. AWS checks it when it is being created using the second argument as the identifier. If there is a VPC with the same ID already, it updates it (if there are changes). If there is no VPC with the given id, it is created. So, in the end, you just create the state you want and AWS either creates new or modifies existing or does nothing if there are no changes in your template.

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