如何将弹性 ip 与 AWS CDK 中的 NAT 实例相关联?

How to associate an elastic ip with a NAT instance in AWS CDK?

我使用 AWS CDK 创建了一个 NAT 实例。

const nat_instance_provider = ec2.NatProvider.instance({
    instanceType: new ec2.InstanceType('t3.micro')
});

然后我创建了一个弹性IP。

const elastic_ip = new ec2.CfnEIP(this, "elastic_ip");

现在我需要将ec2实例与弹性IP相关联。

let ec2Assoc = new ec2.CfnEIPAssociation(this, "Ec2Association", {
    eip: elastic_ip.ref,
    instanceId: <EC2 ID> ???
});

我面临的问题是,到目前为止我找不到获取实例 ID 的方法,我觉得这是一个限制,但我可能会遗漏一些东西。

NAT 实例资源是 vpc 子网的子资源,不直接公开。您可以使用 CDK 的 escape hatch 语法获取对底层 CloudFormation AWS::EC2::Instance 资源的引用。

const vpc = new ec2.Vpc(this, 'MyVpc', {
  natGatewayProvider: nat_instance_provider,
});

// Escape hatch - find the nested child IConstruct by its CDK-assigned id and cast it to ec2.Instance
// finding the ids sometimes requires detective work in the cdk source code or with console.log.
// if the id references are valid, it will have the instanceId
const natInstancePublicSubnet1 = vpc.node.findChild('PublicSubnet1').node.findChild('NatInstance') as ec2.Instance;

const ec2Assoc = new ec2.CfnEIPAssociation(this, 'Ec2Association', {
  eip: elastic_ip.ref,
  instanceId: natInstancePublicSubnet1.instanceId,
});

免责声明:使用逃生舱口是完全可以的,有时是不可避免的。但是,这通常(但不总是)表明您正在使用先进的非标准解决方案“偏离滑雪道”。我个人对您正在尝试的设置知之甚少。