【问题标题】:How to check if a custom VPC already exist using AWS CDK?如何使用 AWS CDK 检查自定义 VPC 是否已存在?
【发布时间】:2021-11-09 22:48:52
【问题描述】:

我正在编写 CDK 脚本并使用默认 VPC,我有以下代码:

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

要使用现有 VPC(非默认),我有以下代码(将按现有标签搜索):

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

我需要在第一次创建 VPC,并在更新时重复使用。像这样的:

尝试使用现有的vpc,如果不存在,则创建它

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);
}

但是我的 try 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

【问题讨论】:

    标签: typescript amazon-web-services try-catch amazon-vpc aws-cdk


    【解决方案1】:

    您不必检查 VPC 是否存在。 AWS 在使用第二个参数作为标识符创建它时对其进行检查。如果已经存在具有相同 ID 的 VPC,则会对其进行更新(如果有更改)。如果没有具有给定 id 的 VPC,则创建它。因此,最后,您只需创建您想要的状态,AWS 要么创建新的,要么修改现有的,或者如果您的模板没有更改,则什么也不做。

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多