Skip to content

Instantly share code, notes, and snippets.

@dpasqua
Created May 11, 2019 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpasqua/6daaa191ef5e4c162033934fa7f70e60 to your computer and use it in GitHub Desktop.
Save dpasqua/6daaa191ef5e4c162033934fa7f70e60 to your computer and use it in GitHub Desktop.
Script to change a ec2 IP with Elastic IP, when ec2 in VPC.
#!/bin/sh
#
# script by Douglas V. Pasqua <douglas.pasqua@gmail.com>
#
# this script is based on original: https://github.com/maxharlow/aws-ip-rotator/blob/master/aws-ip-rotator.sh
# the improvement in this scrtipt is that it works with ec2 in vpc (at releasing the old ip)
#
# To run this script install aws-cli and jq (JSON Processor)
# $ sudo apt install awscli
# $ sudo apt install jq
#
# Configure aws api key:
# $ sudo aws configure
#
# this is not a complete running script. Use or modify as you need.
#get instace-id and public ip of currently ec2. More information about ec2 metada, see:
#https://docs.aws.amazon.com/pt_br/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
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)
#allocate new ip address
NEW_IP=$(aws ec2 allocate-address --query PublicIp | tr -d '"')
#associate new ip
echo "Renew IP: $OLD_IP => $NEW_IP"
aws ec2 associate-address --instance-id $INSTANCE --public-ip $NEW_IP
echo "IP $NEW_IP associated with success."
#release old ip
echo "Releasing $OLD_IP..."
ALLOCATION_ID=$(aws ec2 describe-addresses --public-ips $OLD_IP | jq -r '.Addresses[0].AllocationId')
aws ec2 release-address --allocation-id $ALLOCATION_ID
echo "finished"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment