Created
March 15, 2022 22:10
-
-
Save tayl0r/c2567e31241e8a44a6e26f6653c0d5b3 to your computer and use it in GitHub Desktop.
dynamic dns with AWS route53
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/bash -x | |
# Hosted Zone ID e.g. BJBK35SKXXXX | |
ZONEID="XXXXXXXXXXXXXX" | |
# The CNAME you want to update e.g. scv.tsteil.com | |
RECORDSET=$1 | |
# More advanced options below | |
# The Time-To-Live of this recordset | |
TTL=60 | |
# Change this if you want | |
COMMENT="Auto updating @ `date`" | |
# Change to AAAA if using an IPv6 address | |
TYPE="A" | |
# Get the external IP address | |
IP=`curl -ss https://icanhazip.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 | |
} | |
# Get current dir (stolen from http://stackoverflow.com/a/246128/920350) | |
#DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" | |
LOGFILE="$HOME/tmp/update-route53.log" | |
IPFILE="$HOME/tmp/update-route53.ip" | |
if ! valid_ip $IP; then | |
echo "Invalid IP address: $IP" >> "$LOGFILE" | |
exit 1 | |
fi | |
# Check if the IP has changed | |
if [ ! -f "$IPFILE" ] | |
then | |
touch "$IPFILE" | |
fi | |
if grep -Fxq "$IP" "$IPFILE"; then | |
# code if found | |
echo "IP is still $IP. Exiting" >> "$LOGFILE" | |
exit 0 | |
else | |
echo "IP has changed to $IP" >> "$LOGFILE" | |
# 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", | |
"Type":"$TYPE", | |
"TTL":$TTL | |
} | |
} | |
] | |
} | |
EOF | |
# Update the Hosted Zone record | |
aws route53 change-resource-record-sets \ | |
--hosted-zone-id $ZONEID \ | |
--change-batch file://"$TMPFILE" >> "$LOGFILE" | |
echo "" >> "$LOGFILE" | |
# Clean up | |
rm $TMPFILE | |
# 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