Skip to content

Instantly share code, notes, and snippets.

@Randy1Burrell
Forked from phybros/update-route53.sh
Created November 18, 2017 19:13
Show Gist options
  • Save Randy1Burrell/7104d1401face8513dc6e94927f6023d to your computer and use it in GitHub Desktop.
Save Randy1Burrell/7104d1401face8513dc6e94927f6023d to your computer and use it in GitHub Desktop.
BASH Script to keep Route53 updated with your current external IP address
#!/bin/bash
# (optional) You might need to set your PATH variable at the top here
# depending on how you run this script
# PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Hosted Zone ID e.g. BJBK35SKMM9OE
ZONEID=(
"ZONEID-0"
"ZONEID-1"
"ZONEID-2"
"ZONEID-3"
)
# The CNAME you want to update e.g. hello.example.com
RECORDSET=(
"RECORDSET-0"
"RECORDSET-1"
"RECORDSET-2"
"RECORDSET-3"
)
# More advanced options below
# The Time-To-Live of this recordset
TTL=300
# Change this if you want
COMMENT="Auto updating @ `date`"
# Change to AAAA if using an IPv6 address
TYPE="A"
# Get current dir
# (from http://stackoverflow.com/a/246128/920350)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LOGFILE="$DIR/update-route53-log"
IPFILE="$DIR/update-route53-ip"
# Get the external IP address from OpenDNS (more reliable than other providers)
IP=`dig +short myip.opendns.com @resolver1.opendns.com`
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
# Log and exit if IP is invalid
if ! valid_ip $IP; then
echo "$(date -R) Invalid IP address: $IP" >> "$LOGFILE"
exit 1
fi
# Check if the IP file exists and creates one if it doesn't
if [ ! -f "$IPFILE" ]
then
touch "$IPFILE"
fi
# Log and exit if IP matches current IP address stored in IPFILE
# Else update IP address on amazon.com and log to file
if grep -Fxq "$IP" "$IPFILE"; then
# code if found
echo "$(date -R) IP is still $IP. Exiting" >> "$LOGFILE"
exit 0
else
echo "$(date -R) IP has changed to $IP" >> "$LOGFILE"
zn_iter=0
zn_list_length=${#ZONEID[@]};
for zone in "${ZONEID[@]}";
do
# Fill a temp file with valid JSON
TMPFILE=$(mktemp /tmp/temporary-file.XXXXXXXX)
cat > ${TMPFILE} << EOF
{
"Comment":"$COMMENT",
"Changes":[
{
"Action":"UPSERT",
"ResourceRecordSet":{
"ResourceRecords":[
{
"Value":"$IP"
}
],
"Name":"${RECORDSET[$zn_iter]}",
"Type":"$TYPE",
"TTL":$TTL
}
}
]
}
EOF
# Update the Hosted Zone record
aws route53 change-resource-record-sets \
--hosted-zone-id $zone \
--change-batch file://"$TMPFILE" >> "$LOGFILE"
zn_iter=$(( $zn_iter + 1 ));
echo "" >> "$LOGFILE"
# Clean up
rm $TMPFILE
done
# All Done - cache the IP address for next time
echo "$IP" > "$IPFILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment