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. (MVP)
For reasons I don't understand, an elastic IP is created for each public subnet of the VPC my EC2 instance is within. 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.
Any suggestions?
For me, I have to create the ec2 using the CfnInstance
then use the ec2Instance.ref
inside the 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
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,
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.