Script to change a ec2 IP with Elastic IP, when ec2 in VPC.
This file contains 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/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