Skip to content

Instantly share code, notes, and snippets.

@yyoshiki41
Last active March 23, 2018 08:51
Show Gist options
  • Save yyoshiki41/9398deb9700ba5345d78369b037da929 to your computer and use it in GitHub Desktop.
Save yyoshiki41/9398deb9700ba5345d78369b037da929 to your computer and use it in GitHub Desktop.
#!/bin/bash
# depend on awscli and jq
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
instanceName="nat-instance"
echo "Start to swap eips"
# 1. Get nat-instance Id
instanceId=$(aws ec2 describe-instances --filter "Name=tag:Name,Values=${instanceName}" --query 'Reservations[].Instances[].InstanceId' --output text)
if [ "x${instanceId}" == "x" ]; then
echo "${instanceName} does not exist" && exit 1
fi
echo "${instanceId}"
# 2. Get the current addr allocation Id
currentAllocationId=$(aws ec2 describe-addresses --filters "Name=instance-id,Values=${instanceId}" | jq '.Addresses[].AllocationId')
if [ "x${currentAllocationId}" == "x" ]; then
echo "failed to get a current allocation Id" && exit 1
fi
# 3. Allocate a new addr
newAllocationId=$(aws ec2 allocate-address --domain vpc | jq .AllocationId)
if [ "x${newAllocationId}" == "x" ]; then
echo "failed to allocate a new address" && exit 1
fi
echo "${newAllocationId}"
# 4. Associate a new addr to nat-instance
aws ec2 associate-address --allocation-id "${newAllocationId//\"/}" --instance "${instanceId//\"/}"
if [ $? != 0 ]; then
echo "failed to associate a new address" && exit 1
fi
# 5. Release an old addr
aws ec2 release-address --allocation-id "${currentAllocationId//\"/}"
if [ $? != 0 ]; then
echo "failed to release an old address" && exit 1
fi
echo "success"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment