While working on a CDK script, I encountered a situation where I needed to utilize the default VPC. Here is the code snippet for that:
vpc = ec2.Vpc.fromLookup(this, "UseDefaultVPC", {
isDefault: true
});
In case I need to use an existing non-default VPC, I have this piece of code (which searches based on existing tags):
vpc = ec2.Vpc.fromLookup(this, "UseCustomVPCAlreadyCreated", {
tags: {
environment: project.environment,
project_name: project.name
}
});
The requirement is that the VPC should be created the first time and then reused upon update. It needs to work like this:
Attempt to use an existing VPC, if not found, create one
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);
}
However, the try-catch block is not functioning as expected. The output shows:
It tries twice and fails to hit the catch block:
$ 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