Last active
June 28, 2019 02:12
-
-
Save HackingGate/39cab655e98af836c77087b8fe147dbd to your computer and use it in GitHub Desktop.
AWS EC2 renew IPv4 address by stop-wait-start instance. (no Elastic IPs needed)
This file contains hidden or 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/bash | |
| # From AWS doc | |
| # https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html | |
| # We release your instance's public IP address when it is stopped or terminated. | |
| # Your stopped instance receives a new public IP address when it is restarted. | |
| PATH=$HOME/.local/bin:$PATH | |
| instace_ids="i-1348636c" #change it | |
| sleep_time=30 #change it bigger to prevent fails | |
| function getip() | |
| { | |
| # https://unix.stackexchange.com/a/268612/267632 | |
| aws ec2 describe-instances --instance-ids $instace_ids | grep PublicIpAddress | awk -F ":" '{print $2}' | sed 's/[",]//g' | sed 's/ //' | |
| } | |
| function sleeping() | |
| { | |
| echo -n "Sleeping $sleep_time seconds" | |
| for (( i=0; i<$sleep_time; i++ )); do | |
| sleep 1 | |
| echo -n "." | |
| done | |
| echo "" | |
| } | |
| oldip=$(getip) | |
| echo "{\"oldip\":$oldip}" | |
| aws ec2 stop-instances --instance-ids $instace_ids | |
| sleeping | |
| aws ec2 start-instances --instance-ids $instace_ids | |
| sleeping | |
| sleeping | |
| aws ec2 start-instances --instance-ids $instace_ids | |
| sleeping | |
| sleeping | |
| sleeping | |
| aws ec2 start-instances --instance-ids $instace_ids | |
| newip=$(getip) | |
| echo "{\"newip\":$newip}" | |
| changed=false | |
| if [ $oldip != $newip ]; then | |
| changed=true | |
| fi | |
| echo "{\"changed\":\"$changed\",\"newIP\":\"$newip\",\"oldIP\":\"$oldip\"}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example if you want dynamic dns.
sudo crontab -ethen add the following: