Skip to content

Instantly share code, notes, and snippets.

@cam8001
Created Oct 1, 2021
Embed
What would you like to do?
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