Carlos Fagiani Jr
Carlos Fagiani Jr

Reputation: 158

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

Upvotes: 4

Views: 1479

Answers (1)

szrg
szrg

Reputation: 89

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.

Upvotes: 2

Related Questions