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