[英]How to have the CDK create only one Elastic IP address for use with a single EC2 instance (AWS CDK)
I'm trying to create a Stack using the AWS CDK that will deploy a single EC2 instance, create an Elastic IP and then associate it with that instance.我正在尝试使用将部署单个 EC2 实例的 AWS CDK 创建一个堆栈,创建一个弹性 IP,然后将其与该实例相关联。 (MVP)
(MVP)
For reasons I don't understand, an elastic IP is created for each public subnet of the VPC my EC2 instance is within.由于我不明白的原因,为我的 EC2 实例所在的 VPC 的每个公共子网创建了一个弹性 IP。 I expect that only one should be created, not three.
我希望只创建一个,而不是三个。
Below is my simplified code:下面是我的简化代码:
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,
});
I've tried to use a CfnEIPAssociation instance of the 'instanceID' property within the CfnEIP but still have the same problem.我尝试在 CfnEIP 中使用“instanceID”属性的 CfnEIPAssociation 实例,但仍然遇到同样的问题。
Any suggestions?有什么建议么?
For me, I have to create the ec2 using the CfnInstance
then use the ec2Instance.ref
inside the CfnEIPAssociation
.对我来说,我必须使用
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
});
(Apologies, this is months after solving it) (抱歉,这是解决它几个月后)
I believe the issue was the vpcSubnets field, below is the working code I have today我相信问题是 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,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.