Skip to content

Instantly share code, notes, and snippets.

@kgorskowski
Created January 27, 2017 11:33
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 kgorskowski/3fd862ce8e53b6098730566a85393165 to your computer and use it in GitHub Desktop.
Save kgorskowski/3fd862ce8e53b6098730566a85393165 to your computer and use it in GitHub Desktop.
Reassociate AWS EIP (needs awscli, jq and the corresponding iam permissions)
#!/bin/bash
# Helper Functions
get_instance_region() {
if [ -z "$AWS_REGION" ]; then
AWS_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document \
| grep -i region \
| awk -F\" '{print $4}')
fi
echo $AWS_REGION
}
AWS_CLI="aws --region $(get_instance_region)"
get_instance_id() {
curl -s http://169.254.169.254/latest/meta-data/instance-id
return $?
}
INSTANCE_ID=$(get_instance_id)
if [ $? != 0 -o -z "$INSTANCE_ID" ]; then
error_exit "Unable to get this instance's ID; cannot continue."
fi
AWS_CLI="aws --region $(get_instance_region)"
EIP_ALLOCATION=$YOUR-EIP-ALLOCATION-HERE
associate_ip() {
$AWS_CLI ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $EIP_ALLOCATION
}
check_association() {
$AWS_CLI ec2 describe-addresses --allocation-ids $EIP_ALLOCATION | jq '.Addresses[].InstanceId' --raw-output
return $?
echo $?
}
CURRENT_INSTANCE=$(check_association)
echo "$EIP_ALLOCATION is currently associated to $CURRENT_INSTANCE, we are Instance $INSTANCE_ID"
if [ "$CURRENT_INSTANCE" == "$INSTANCE_ID" ]; then
echo "EIP is already associated to this instance"
exit 1
else
echo "ok, will reassociate"
fi
associate_ip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment