Last active
March 18, 2020 08:25
-
-
Save cam8001/d435d4e55ffcee358832eea19962b204 to your computer and use it in GitHub Desktop.
EC2 User Data script to allocate an EIP on launch.
This file contains 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
#!/bin/bash | |
# | |
# Associate a given elastic IP with an instance on boot. | |
# | |
# Useful in autoscaling groups with a max-size of 1, where you always want the | |
# same IP for a given instance. | |
# | |
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id) | |
AWS_DEFAULT_REGION=ap-southeast-2 | |
# Associate this EIP on launch. | |
ALLOC_ID=YOUR_EIP_ALLOC_ID | |
echo "Updating packages..." | |
# Update packages. | |
apt-get update -y | |
# Force grub to update in a silent mode | |
DEBIAN_FRONTEND=noninteractive apt-get -y -o DPkg::options::="--force-confdef" -o DPkg::options::="--force-confold" -qq --force-yes upgrade | |
# Install the awscli | |
if ! [ -x "$(command -v aws)" ]; then | |
echo "Installing awscli..." | |
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" | |
yes | unzip awscliv2.zip | |
yes | ./aws/install | |
fi | |
# Install jq | |
if ! [ -x "$(command -v jq)" ]; then | |
echo "Installing jq..." | |
snap install jq | |
fi | |
# Get instance creds. | |
# @see https://github.com/pierreg256/eip/blob/master/auto-ip.sh | |
# @see https://gist.github.com/fgassert/8923461 | |
# @see https://gist.github.com/odessky/e7b8b31e3b710cf3e29e85339d4ec5e6 | |
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/) | |
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') | |
# Now we can associate the address. | |
echo "Running: aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID --allow-reassociation" | |
aws 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 "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