I have created an Ec2 auto-scaling group which runs only one instance. This Ec2 instance is associated with Elastic IP. When Ec2 instance gets terminated, the Elastic IP is kept attaching to the terminated instance and auto-scaling spins up a new instance with no Elastic IP.
Is there any good way to detach that Elastic IP when the instance is terminated and attach the same Elastic IP to newly created EC2 instance?
I also try to use EC2 user data to attach elastic IP by using these commands:
#!/bin/bash
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id 4x.xx6.xx0.xx
but it didn't work too. Moreover, I added proper association role to ec2.
I am thinking of setting up AWS EventBridge rule to catch the instance status change and that rule will eventually trigger lambda function which will disassociate the Elastic IP from the terminated EC2 instance and associate it to the newly created EC2.
Is this approach is good or there is some better and efficient approach available?
It sounds like you have activated Instance Metadata Service Version 2 (IMDSv2), which requires token-passing for extra security.
You can return it to Version 1 via Actions / Instance Settings / Modify instance metadata options and make IMDSv2 'Optional'.