Created
January 27, 2017 11:33
-
-
Save kgorskowski/3fd862ce8e53b6098730566a85393165 to your computer and use it in GitHub Desktop.
Reassociate AWS EIP (needs awscli, jq and the corresponding iam permissions)
This file contains hidden or 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 | |
# 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