Here, we will learn about, how to assign a Elastic IP/Public to an Instance/Server from an Auto Scaling Group in AWS.
Use Case:
Consider that we wanted to allow SSH Connection from your office premises to one of EC2 Instance within Auto Scaling Group (ASG) in AWS. The IT Admin of office will now require a static public IP Address to permit connectivity from office to your Ec2 Instance from ASG. In the event that if public IP address continues to change, the IT Admin continuously needs to update the IP in Firewall to allow connection from Server.
To overcome this situation, we can create an ASG for an EC2 Instance with Min capacity as 1 and then we can assign an Elastic IP/Public IP to our ASG Server.
Solution:
Assuming that we have already created a Launch Template, AMI, Auto-Scaling Group and Launched an EC2 Instance from the Auto Scaling Group.
Now, navigate to the Elastic IP Tab in AWS Console. Click Allocate New Address and choose the option as Amazon Pool. A new public Elastic IP will be assigned to our AWS account from the Amazon’s pool of IP Address.
We have assigned EIP 44.218.XX.XXX after performing this action. Make note of the Association ID looks like “eipalloc-07158c131211dc2b3”.
Now navigate to the Instance where you wanted to associate this Elastic IP. Click on “Create Template from Instance” and choose the option as “Create New Template Version from an Instance”. Select the Launch Template and scroll down to the User Data of Advance Details Section towards the end.


Now go to the Launch Template. Select the Launch Template you want to edit then Click Modify template (Create new version). Scroll down to User Data of Advanced details section towards the end.

Add following code to User Data Section. Click on Create Template (or Create Template Version).
#!bin/bash
aws ec2 disassociate-address --public-ip 44.218.XX.XXX
aws ec2 associate-address --instance-id "$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)" --allocation-id eipalloc-07158c131211dc2b3
*Change the IP address and Allocation Id as per your requirement.
The Scripts in User data Section gets executed whenever the New Instance created in ASG. Using this, we instruct the Instance to dis-associate the Elastic IP forcefully, even if it is associated with an other instance. The second command associates the Elastic IP address with current Instance.
Proof:
Let’s check whether it’s working or not.
Terminate the current instance running under ASG group. Wait till the ASG launches a new instance to fill the gap.
Click on Newly created instance and check its IP. The EIP will now be associated with the new Instance.

Whenever the new instance will create this IP will be detached from the Old Instance and will remain associated with the new Instance. This function will repeat whenever a new Instance gets launched.
Please let me know, in case of any errors.
Thank You!!