从 aws-cdk 生成的 VPC 定义中获取 EIP 作为输出

Get EIP as output from aws-cdk generated VPC definition

通过

有一个 vpc 定义
 const vpc = new ec2.Vpc(this, 'SomeVPC', {
        cidr: '10.0.0.0/16',
        maxAzs: 2,
 });

在后台它为 NAT 网关创建了 2 个 EIP

"SomeVPCPublicSubnet1EIP58E3D6C5": {
  "Type": "AWS::EC2::EIP",
  "Properties": {
    "Domain": "vpc"
  }
}

如何获取对它们的引用并通过 CfnOutput 导出?像这样:

new CfnOutput(this, "ExternalIPOutput", {value: <some magic call to get SomeVPCPublicSubnet1EIP58E3D6C5.ref()>})

已经有一段时间了,但我今天遇到了这个问题,这就是我设法处理它并获取 EIP 的方式 -

代码段:


// Create new VPC
const vpc = new ec2.Vpc(this, 'VPC', {
    cidr: props.customCidr,
    maxAzs: 2,
    subnetConfiguration: [
        {
            name: 'Private',
            subnetType: ec2.SubnetType.PRIVATE
        },
        {
            name: 'Public',
            subnetType: ec2.SubnetType.PUBLIC
        }
    ]
});

// Get Elastic IP 
vpc.publicSubnets.forEach((subnet, index) => {
  // Find the Elastic IP
  const EIP = subnet.node.tryFindChild('EIP') as ec2.CfnEIP
  new cdk.CfnOutput(this, `output-eip-${index}`, { value: EIP.ref });
})

输出: