In my aws cdk code, i'm using an elastic ip for a bastion host as below.
const eip = new ec2.CfnEIP(this, "Bast-host1")
const bast_host = new ec2.BastionHostLinux(this, "myproj-Bhost", {
vpc,
subnetSelection: {subnetType: ec2.SubnetType.PUBLIC},
machineImage: ec2.MachineImage.latestAmazonLinux({
userData: ec2.UserData.custom('Content-Type: multipart/mixed;)
}),
})
new ec2.CfnEIPAssociation(this, "HostAllocation", {
eip: elasticIP.ref,
instanceId: bast_host.instance.instanceId
});
But each and every time when i deploy the cloudformation stack, the elastic IP is being recreated. Is there any way to persist an elastic ip on each time the cloudformation stack runs?
If the elastic ip address is created using CDK, you will lose it with the other resources once
destroycommand is executed.I don't recommend creating it together with your IAC stacks as it makes whitelisting of IP addresses with other partners and sibling networks a mess.
How I personally ensure that elastic IP address stays alive when using any IAC tooling (CDK, Terraform, CloudFormation) is by manually creating an Elastic IP address using ClickOps and then take note of its
Allocation ID.I then pass this Allocation ID as a variable to my IAC template as a parameter. This allows me to destroy the IAC stack without losing the IP address when doing so.
To associate it with EC2 instances that you plan to create with CDK, just use the following syntax and pass the allocation ID as an environment variable or a parameter in your CDK templates.