Created
October 1, 2021 09:38
-
-
Save cam8001/617f1032a84b638a6dc64aaf86bef991 to your computer and use it in GitHub Desktop.
Associate Elastic IP on every boot even with custom AMI (eg for autoscaling)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Content-Type: multipart/mixed; boundary="//" | |
MIME-Version: 1.0 | |
--// | |
Content-Type: text/cloud-config; charset="us-ascii" | |
MIME-Version: 1.0 | |
Content-Transfer-Encoding: 7bit | |
Content-Disposition: attachment; filename="cloud-config.txt" | |
#cloud-config | |
cloud_final_modules: | |
- [scripts-user, always] | |
--// | |
Content-Type: text/x-shellscript; charset="us-ascii" | |
MIME-Version: 1.0 | |
Content-Transfer-Encoding: 7bit | |
Content-Disposition: attachment; filename="userdata.txt" | |
#!/bin/bash | |
ROLE=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/) | |
CR=$(curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE/) | |
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) | |
export AWS_ACCESS_KEY_ID=$(echo $CR | jq -r '.AccessKeyId') | |
export AWS_SECRET_ACCESS_KEY=$(echo $CR | jq -r '.SecretAccessKey') | |
export AWS_SESSION_TOKEN=$(echo $CR | jq -r '.Token') | |
AWS_DEFAULT_REGION=ap-southeast-2 | |
ALLOC_ID=eipalloc-deadb33f | |
# Now we can associate the address. | |
echo -e "Running: aws --region=$AWS_DEFAULT_REGION ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --allow-reassociation" | |
aws --region=$AWS_DEFAULT_REGION ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --allow-reassociation | |
IPv4=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4) | |
echo -e "This instance now has public IPv4 $IPv4" | |
--//-- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/