【问题标题】:How to associate an elastic ip with a NAT instance in AWS CDK?如何将弹性 ip 与 AWS CDK 中的 NAT 实例关联?
【发布时间】:2022-01-13 23:32:07
【问题描述】:

我使用 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 的方法,我觉得这是一个限制,但我可能会遗漏一些东西。

【问题讨论】:

    标签: amazon-web-services amazon-ec2 aws-cdk


    【解决方案1】:

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

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

    【讨论】:

    • 嘿@fedonev,谢谢你的回答,这个答案很好,我需要使用NAT实例而不是NAT网关来省钱,因为NAT网关太贵了,我也需要有实例中的静态 IP,以便它可以被我必须使用的其他资源列入白名单。我真的不认为有更好/标准/成本效益高的方法来实现这一目标。如果您有额外的 cmets,请不胜感激。
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 2018-09-14
    • 2020-10-26
    • 1970-01-01
    • 2017-08-23
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多