Skip to content

Instantly share code, notes, and snippets.

@cam8001
Created October 1, 2021 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cam8001/617f1032a84b638a6dc64aaf86bef991 to your computer and use it in GitHub Desktop.
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)
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"
--//--
@cam8001
Copy link
Author

cam8001 commented Oct 1, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment