Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 201
Carlos Fagiani Jr Avatar asked Oct 28 '25 17:10

Carlos Fagiani Jr


1 Answers

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.

like image 50
szrg Avatar answered Oct 31 '25 06:10

szrg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!