Skip to content

Instantly share code, notes, and snippets.

@muhqu
Created May 16, 2014 07:59
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 muhqu/c64af92f749c8a6718ea to your computer and use it in GitHub Desktop.
Save muhqu/c64af92f749c8a6718ea to your computer and use it in GitHub Desktop.
#!/bin/bash
EIP="$1" # "50.16.123.123"
ASG="$2" # "www"
if [ -z "$EIP" ] || [ -z "$ASG" ]; then
echo "Usage: $(basename $0) EIP ASG"
echo "Example: $(basename $0) 50.16.123.123 www"
exit 1;
fi
insIDbyADDR() {
aws ec2 describe-addresses --public-ips "$1" \
| jq -r '.Addresses[] | .InstanceId'
}
insIDsByASG() {
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names "$1" \
| jq -r '.AutoScalingGroups[] | .Instances | map(select(.LifecycleState == "InService"))[] | .InstanceId'
}
ALLOWED_IDS=$(insIDsByASG $ASG)
FIRST_ALLOWED_ID=$(echo $ALLOWED_IDS | awk '{print $1; exit}')
if [ -z "$FIRST_ALLOWED_ID" ]; then
echo >&2 "Error: unable to find any allowed IDs... aborting. (EIP:$EIP ASG:$ASG)";
exit 1;
fi
CURR_ID=$(insIDbyADDR $EIP)
if [ -z "$CURR_ID" ]; then
echo >&2 "Warn: Elastic IP ($EIP) not associated!"
echo $FIRST_ALLOWED_ID | xargs -t aws ec2 associate-address --public-ip $EIP --instance-id
else
OK="no"
for ALLOWED_ID in $ALLOWED_IDS; do
if [ "$ALLOWED_ID" = "$CURR_ID" ]; then
OK="yep"
fi
done
if [ "$OK" = "no" ]; then
echo >&2 "Warn: Elastic IP ($EIP) associated with wrong instance ($CURR_ID)..."
echo $FIRST_ALLOWED_ID | xargs -t aws ec2 associate-address --public-ip $EIP --instance-id
else
echo "Elastic IP ($EIP) associated with instance ($CURR_ID). fine.. no need to change!"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment