How to Associate Elastic IP with EC2 Instance using CloudFormation
Dear Reader, hope you are doing well. In my previous post, we talked about Elastic IP and its significance with respect to EC2 Instances.
We also allocated an elastic IP to our account and then associated that with one of our running instances. In this post, we will do the same thing but instead of doing it manually, we will do it using CloudFormation.
Basic Overview
When you launch an EC2 instance in a default VPC, a public IP gets automatically assigned to your instance at launch. You can use that public IP to connect to(SSH) your instance or to access it over the internet via public IP or public DNS.
So far so good 🙂
However, usually when you stop your instance and start it again, due to the dynamic nature of pubic IP, your instance’s public IP changes and you no longer access your instance using the previous pubic IP.
It becomes even more difficult when you have A records in route 53 mapping to your instance’s public IP. It simply doesn’t make sense to update the A record every time your instance changes the IP.
One of the solutions in such cases is to assign an elastic IP which is a static public IP and will not change. Read my previous post to understand it in even more detail (Link below).
Suggested Read: How to Assign an Elastic IP to your EC2 Instance in AWS
Steps to Associate Elastic IP with EC2 Instance using CloudFormation
Let’s see the step-by-step instructions to associate Elastic IP with EC2 Instance using CloudFormation
- Step 1: Permission
- Step 2: Prepare a template
- Step 3: Create a Stack using the prepared template
- Step 4: Verifying EIP Association with EC2
- Clean Up
Step 1: Permissions to Associate Elastic IP with EC2 Instance using CloudFormation
If you are not an admin user, you should at least provide below mentioned permissions explicitly to your user/role that will create the CloudFormation Stack.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1634732138851",
"Action": [
"ec2:AllocateAddress",
"ec2:AssociateAddress",
"ec2:ReleaseAddress",
"ec2:StartInstances",
"ec2:StopInstances",
"ec2:TerminateInstances",
"ec2:DisassociateAddress",
"ec2:RunInstances"
]
}
]
}
Note: You will also need cloudformation:* to do CloudFormation stack operations. Also for creating this stack if you face a permission issue, you can try ec2:*
Step 2: Prepare a template
You can use YAML or JSON for your template. I prefer YAML for writing my templates. But don’t worry, If you want it in JSON, I will provide a JSON template as well. You can also convert a JSON template to YAML and Vice Versa using this tutorial.
As you might already know, before we can associate an elastic IP to the EC2 instance, we need to allocate an elastic IP to our account. Once allocated, you can associate it with any of your instances.
Allocate Elastic IP to Your Account
To allocate an elastic IP to your account, all you need is an AWS::EC2::EIP resource.
DemoElasticIP:
Type: AWS::EC2::EIP
Okay, so we know how to allocate an EIP but what about associating them with an actual instance?
Well, the simplest way to associate an Elastic IP to an EC2 instance is using the InstanceId property of AWS::EC2::EIP resource.
That means, while allocating an elastic IP to your AWS account using CloudFormation, you have an option to specify the AWS EC2 instance ID to which you would like to associate this EIP. for example-
DemoElasticIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
InstanceId: !Ref DemoInstance
Few things to note there –
- Domain is used to specify whether the elastic IP is to be used with an instance in VPC or in EC2-Classic
- VPC: vpc
- EC2-Classic: standard
- If your region supports EC2-Classic, the default value of this property is standard otherwise vpc
- InstanceId property is available to you to associate this newly created EIP with an EC2 instance.
- I have used !Ref: DemoInstance in InstanceId property because I am creating EC2 in the same template and using !Ref on the logical ID of an EC2 resource returns its InstanceId.
- For other available properties for this resources, check official documentation
Template Example to Associate Elastic IP with EC2 Instance using CloudFormation in YAML
In this template, we are launching an EC2 instance, allocating an elastic IP and associating that IP with our EC2 instance.
AWSTemplateFormatVersion: '2010-09-09'
Description: Template to Create an EC2 instance, EIP and associate with instance
Parameters:
ImageId:
Type: String
Description: 'Linux 2 AMI for Ireland eu-west1 Region'
Default: 'ami-0fc970315c2d38f01'
InstanceType:
Type: String
Description: Choosing t2 micro because it is free
Default: t2.micro
KeyName:
Description: SSH Keypair to login to the instance
Type: AWS::EC2::KeyPair::KeyName
Default: demokeypair
Resources:
DemoInstance:
Type: 'AWS::EC2::Instance'
Properties:
ImageId: !Ref ImageId
InstanceType: !Ref InstanceType
KeyName: !Ref KeyName
#Allocate an Elastic IP in your Account
DemoElasticIP:
Type: AWS::EC2::EIP
Properties:
Domain: vpc
InstanceId: !Ref DemoInstance
Outputs:
DemoInstanceId:
Description: Instance Id
Value: !Ref DemoInstance
Template example to Associate Elastic IP with EC2 Instance using CloudFormation in JSON
{
"AWSTemplateFormatVersion": "2010-09-09",
"Description": "Template to Create an EC2 instance, EIP and associate with instance",
"Parameters": {
"ImageId": {
"Type": "String",
"Description": "Linux 2 AMI for Ireland eu-west1 Region",
"Default": "ami-0fc970315c2d38f01"
},
"InstanceType": {
"Type": "String",
"Description": "Choosing t2 micro because it is free",
"Default": "t2.micro"
},
"KeyName": {
"Description": "SSH Keypair to login to the instance",
"Type": "AWS::EC2::KeyPair::KeyName",
"Default": "demokeypair"
}
},
"Resources": {
"DemoInstance": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": {
"Ref": "ImageId"
},
"InstanceType": {
"Ref": "InstanceType"
},
"KeyName": {
"Ref": "KeyName"
}
}
},
"DemoElasticIP": {
"Type": "AWS::EC2::EIP",
"Properties": {
"Domain": "vpc",
"InstanceId": {
"Ref": "DemoInstance"
}
}
}
},
"Outputs": {
"DemoInstanceId": {
"Description": "Instance Id",
"Value": {
"Ref": "DemoInstance"
}
}
}
}
Step3: Create a Stack using the prepared template
Now, we know the basics and we have the template so let’s go and create the stack.
- Grab the YAML or JSON template from above at your convenience.
- Change parameters like ImageId, InstanceType and KeyName with your own AMI Id, instance type and name of keypair respectively
- Save the template with .yml or .json as per the choice of template and follow the below steps.
- Login to AWS Management Console, navigate to CloudFormation and click on Create stack
- Click on “Upload a template file”, upload your saved .yml or .json file and click Next
- Enter the stack name and click on Next. In configuration, keep everything as default and click on Next.
- In the events tab of the stack, you can view the status.
- Once the stack is successfully created, you can check the “Resources” tab to see all that’s created by this template.
- Navigate to the EC2 instance and verify that EIP is created and associated with your instance.
Resources Created:
As you can see in the Resources tab of the created stack, two resources have been created. An EC2 instance and an Elastic IP. You can view details by clicking on the physical ID as underlined below screenshot
You can also use AWS CLI to deploy your CloudFormation Template.
Step 4: Verifying EIP Association with EC2:
Click on instance ID to see EC2 instance details. In the details screen, you will see that Elastic IP and public IP are the same. The good news is that now if you stop your instance and start it again, it is not going to change 🙂
Clean Up
If you are creating this EC2 and EIP just for learning purposes. Don’t forget to delete your CloudFormation stack so that your instance and elastic IP are deleted and you don’t bear any cost.
Happy Learning !!!
You can also setup a budget in your AWS account to never be billed unnecessarily.
Conclusion:
In this post, we learned how to associate elastic IP with EC2 Instance using CloudFormation.
We learnt-
- A bit about Elastic IP and its need
- How to allocate an elastic IP using CloudFormtion
- Associating the created EIP with the EC2 instance using CloudFormation
I hope you found this post helpful. If you find any issues, please feel free to reach me in the comment section. I would be more than happy to reply to your comment.
Enjoyed the content?
Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.
Don’t forget to motivate me by-
- Adding a comment below on what you liked and what can be improved.
- Follow us on
- Share this post with your friends
Suggested Read:
- How to Launch an EC2 Instance in AWS Step by Step
- Understand IAM PassRole to Secure your AWS Infrastructure
- Attach an IAM Role to an EC2 Instance using CloudFormation
- AWS EC2 instance Purchasing Options: All you need to know
- Install Apache Web Server on a EC2 instance in AWS
- User User data Script to Bootstrap your EC2 instance
2 thoughts on “How to Associate Elastic IP with EC2 Instance using CloudFormation”
Hello CloudKatha,
I am Darshan from mumbai, Want your help regarding AWS CloudFormation and Elastic Ip allocation to EC2 instances. I saw your post (https://cloudkatha.com/how-to-associate-elastic-ip-with-ec2-instance-using-cloudformation/) here and it was helpful. Will you please help me regarding the following concern, I want to allocate the Elastic Ip addresses to the newly created Instances from the EC2-fleet, but get the error (InvalidInstanceID.Malformed) while allocating the Elastic Ip address to the EC2-fleet.
I have searched for the errors but didn’t get any solution.
I have attached my template below for your reference, your help will be highly appreciated.
Hello Darshan, I feel in case of EC2 fleet you should use an ALB to provide you with static DNS. Any specific reasons you are not going for that?