如何让CDK仅创建一个弹性IP地址以用于单个EC2实例(AWS CDK)

时间:2020-06-08 15:45:23

标签: typescript amazon-ec2 amazon-vpc aws-cdk elastic-ip

我正在尝试使用AWS CDK创建一个堆栈,该堆栈将部署一个EC2实例,创建一个弹性IP,然后将其与该实例关联。 (MVP)

出于我不了解的原因,为EC2实例所在的VPC的每个公共子网创建了一个弹性IP。我希望只能创建一个,而不是三个。

下面是我的简化代码:

const vpc = new Vpc(this, 'VPC');
const securityGroup = new SecurityGroup(this, 'SecurityGroup', {
  vpc,
});
const ec2Instance = new Instance(this, 'EC2Instance', {
  vpc,
  instanceType: new InstanceType('t2.small'),
  machineImage: ubuntuImage, // searched for elsewhere
  keyName: 'keynamehere',
  vpcSubnets: { subnets: [vpc.publicSubnets[0]] },
});
const eip = new CfnEIP(this, 'Server IP', {
  instanceId: ec2Instance.instanceId,
});

我尝试在CfnEIP中使用'instanceID'属性的CfnEIPAssociation实例,但是仍然存在相同的问题。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

对我来说,我必须使用CfnInstance创建ec2,然后在ec2Instance.ref内部使用CfnEIPAssociation

    const instance = new ec2.CfnInstance(this, 'CccgEc2', {
      imageId: 'ami-07d0cf3af28718ef8',
      instanceType: 't2.micro',
      keyName: 'id_rsa',
      monitoring: false,
      securityGroupIds: [
        mySecurityGroup.securityGroupId
      ],
      subnetId: vpc.publicSubnets[0].subnetId,
      // iamInstanceProfile: 'ec2-role'
    });

    const eip = new ec2.CfnEIP(this, 'Server IP', {});

    new ec2.CfnEIPAssociation(this, 'ea', {
      eip: eip.ref,
      instanceId: instance.ref
    });

答案 1 :(得分:1)

(抱歉,这是解决问题的几个月后了)

我认为问题在于vpcSubnets字段,以下是我今天拥有的工作代码

const ec2Instance = new Instance(this, "Instance", {
      vpc: supportStack.vpc,
      instanceType: new InstanceType("t2.nano"),
      machineImage: ubuntuImage,
      securityGroup: supportStack.securityGroup,
      vpcSubnets: { subnetType: SubnetType.PUBLIC }, // 
      userData,
    });
    supportStack.bucket.grantRead(ec2Instance);
    new CfnEIPAssociation(this, "ElasticIpAssociation", {
      eip: eip.ref,
      instanceId: ec2Instance.instanceId,
    });