Skip to content

Instantly share code, notes, and snippets.

@kwilczynski
Last active October 8, 2017 21:35
Show Gist options
  • Save kwilczynski/449e7132460c2d004cd0c3882f21cb14 to your computer and use it in GitHub Desktop.
Save kwilczynski/449e7132460c2d004cd0c3882f21cb14 to your computer and use it in GitHub Desktop.
Associate Elastic IP to a Bastion host running in a Auto-Scaling Group (ASG).
#!/bin/bash
set -e
set -u
set -o pipefail
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# The name of the EC2 tag that holds the Elastic IP address to use.
readonly TAG_NAME='PublicIP'
readonly EC2_METADATA_URL='http://169.254.169.254/latest/meta-data'
readonly LOCK_FILE="/var/lock/$(basename -- "$0").lock"
export DEBIAN_FRONTEND=noninteractive
export DEBCONF_NONINTERACTIVE_SEEN=true
# Make sure files are 644 and directories are 755.
umask 022
[[ -e "/proc/$(cat $LOCK_FILE 2>/dev/null)" ]] || rm -f $LOCK_FILE
if (set -o noclobber; echo $$ > $LOCK_FILE) &>/dev/null; then
# Make sure to remove the temporary
# file when terminating, and clean-up
# the lock-file too.
trap \
"rm -f $LOCK_FILE; exit" \
HUP INT KILL TERM QUIT EXIT
# Refresh packages index only when needed.
UPDATE_STAMP='/var/lib/apt/periodic/update-success-stamp'
if [[ ! -f $UPDATE_STAMP ]] || \
(( $(date +%s) - $(date -r $UPDATE_STAMP +%s) > 300 )); then
apt-get -qq update
fi
# Install AWS CLI and curl, if needed.
PACKAGES=(curl awscli)
for package in "${PACKAGES[@]}"; do
if ! dpkg -s $package &>/dev/null; then
apt-get -qq install --assume-yes $package >/dev/null
fi
done
# Fetch the EC2 instance ID.
INSTANCE_ID=$(curl -s ${EC2_METADATA_URL}/instance-id)
# Extract the region name.
REGION=$(curl -s ${EC2_METADATA_URL}/placement/availability-zone | sed -e 's/\w$//')
# Fetch the EC2 instance tag which contains
# the Elastic IP that should be used when
# requesting the re-assotiation.
PUBLIC_IP_ADDRESS=$(aws ec2 describe-tags \
--query 'Tags[*].Value' \
--filters "Name=resource-id,Values=${INSTANCE_ID}" "Name=key,Values=${TAG_NAME}" \
--region $REGION --output 'text' 2>/dev/null)
# Make sure that the EC2 tag was actually set.
if [[ "x${PUBLIC_IP_ADDRESS}" == "x" ]]; then
echo "The '${TAG_NAME}' tag is empty or has not been set, aborting..."
exit 1
fi
# Request the Elastic IP address to
# be assigned to this EC2 instance.
aws ec2 associate-address \
--public-ip $PUBLIC_IP_ADDRESS \
--instance-id $INSTANCE_ID \
--region $REGION
rm -f $LOCK_FILE &>/dev/null
# Reset traps to their default behaviour.
trap - HUP INT KILL TERM QUIT EXIT
else
echo "Unable to create lock file (current owner: "$(cat $LOCK_FILE 2>/dev/null)")."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment