Search code examples
amazon-web-servicesamazon-ec2aws-auto-scalingelastic-ip

how to allocate elastip ip to autoscaling group with 1 instance


I have 1 instance in auto scaling group with min = 1 max = 1 and desired = 1 I also have an elastic ip which i want to assign single instance and also when this once instance goes down, the elastic ip should be released and allocated to the new instance. I have attached admin policy with the role which is attached in the launch configuration for ASG. I have added below information in user data in launch template but my elastic ip is still not getting associated with new instance. I really need help with this please

 #!/bin/bash
 InstanceID=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id`
 Allocate_ID= 'eipalloc-0d54643260cd69141'
 aws ec2 associate-address --instance-id $InstanceID --allocation-id $Allocate_ID

Solution

  • You'll need to disassociate the address from the instance to which the EIP is attached to before associating it again.

    This will do the job:

    #!/bin/bash
    
    ALLOCATE_ID="eipalloc-0d54643260cd69141"
    
    # Release the EIP if it is currently associated with an instance
    aws ec2 disassociate-address --association-id "$ALLOCATE_ID" || true
    
    # Associate address to this instance
    INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
    aws ec2 associate-address --instance-id "$INSTANCE_ID" --allocation-id "$ALLOCATE_ID"