Skip to content

Instantly share code, notes, and snippets.

@HackingGate
Last active June 28, 2019 02:12
Show Gist options
  • Save HackingGate/39cab655e98af836c77087b8fe147dbd to your computer and use it in GitHub Desktop.
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)
#!/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\"}"
@HackingGate
Copy link
Author

Example if you want dynamic dns.
sudo crontab -e then add the following:

# After rebooting.
@reboot /usr/local/bin/cf-ddns.sh >> /var/log/cf-ddns.log 2>&1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment