Skip to content

Instantly share code, notes, and snippets.

@schwartz1375
Last active June 27, 2023 19:28
Show Gist options
  • Save schwartz1375/b2ee9a652c15b650fb9b701348a68164 to your computer and use it in GitHub Desktop.
Save schwartz1375/b2ee9a652c15b650fb9b701348a68164 to your computer and use it in GitHub Desktop.
Bash script rotates the public IP address of an Amazon EC2 instance.
#!/usr/bin/env bash
function error_exit
{
echo "$1" 1>&2
exit 1
}
case $1 in
'start')
SCHEDULE='*/10 * * * *' # every ten minutes
(crontab -l 2> /dev/null; echo "$SCHEDULE $(pwd)/$(basename $0)") | crontab - ;;
'stop')
crontab -l | grep -v $(basename $0) | crontab - ;;
*)
INSTANCE=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
OLD_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
OLD_ALLOCATION=$(aws ec2 describe-addresses --public-ips $OLD_IP --query Addresses[0].AllocationId --output text)
if [ $? -ne 0 ]; then
error_exit "Failed to retrieve the old allocation ID. Aborting."
fi
NEW_IP=$(aws ec2 allocate-address --query PublicIp --output text)
if [ $? -ne 0 ]; then
error_exit "Failed to allocate a new address. Aborting."
fi
echo ''
echo "Old IP: $OLD_IP"
echo "New IP: $NEW_IP"
echo ''
echo 'Associating new IP...'
aws ec2 associate-address --instance-id $INSTANCE --public-ip $NEW_IP
if [ $? -ne 0 ]; then
aws ec2 release-address --public-ip $NEW_IP
error_exit "Failed to associate the new IP address. Released the new IP and aborting."
fi
echo 'Releasing old IP...'
aws ec2 release-address --allocation-id $OLD_ALLOCATION
if [ $? -ne 0 ]; then
error_exit "Failed to release the old IP address. Manual intervention required."
fi
esac
# The EC2 instance needs an IAM role with the following policy attached:
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Effect": "Allow",
# "Action": [
# "ec2:DescribeAddresses",
# "ec2:AllocateAddress",
# "ec2:AssociateAddress",
# "ec2:ReleaseAddress"
# ],
# "Resource": "*"
# }
# ]
# }
# Remember to replace "*" with the ARNs of specific resources if necessary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment