summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJesse Morgan <jesse@jesterpm.net>2018-04-23 09:57:06 -0700
committerJesse Morgan <jesse@jesterpm.net>2018-04-23 09:57:06 -0700
commit5d0800e8a6b74a536992d10c57d9126f0048e98f (patch)
tree9370b2d976890c9d675642b24fc0006591e195f4
parentaf87be48b6cc85aaf142725acef73c8440bd52a6 (diff)
Add update-dyndns script.
-rwxr-xr-xupdate-dyndns111
1 files changed, 111 insertions, 0 deletions
diff --git a/update-dyndns b/update-dyndns
new file mode 100755
index 0000000..5ac19e0
--- /dev/null
+++ b/update-dyndns
@@ -0,0 +1,111 @@
+#!/bin/bash
+
+##
+## Update a Route53 record with this host's IP addresses.
+##
+## $DIR/.dyndns/config should contain something like:
+## ZONEID="AWS_ZONE_ID"
+## TTL=60
+## ENABLE_IP6=true
+## ENABLE_IP4=false
+##
+## Adapted from https://willwarren.com/2014/07/03/roll-dynamic-dns-service-using-amazon-route53/
+##
+
+DIR=$HOME/.dyndns
+
+if [ ! -f $DIR/config ]; then
+ echo "Config is missing. Exiting."
+ exit 1
+fi
+
+source $DIR/config
+
+RECORDSET=$(hostname --fqdn)
+COMMENT="Auto updating @ `date`"
+
+IP4=$(dig +short myip.opendns.com @resolver1.opendns.com)
+IP6=$((ip -6 addr list|grep inet6|grep global|grep -v temporary|awk '{print $2}'; ip -6 addr list|grep inet6|grep global|grep temporary|awk -F '{print $2}')|head -n1|cut -d/ -f1)
+
+function valid_ip4()
+{
+ 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
+}
+
+function update_dns() {
+ local IP=$1
+ local TYPE=$2
+ local 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"
+ ret="$?"
+ echo
+
+ # Clean up
+ rm $TMPFILE
+
+ return $ret
+}
+
+IP4FILE="$DIR/ip4"
+IP6FILE="$DIR/ip6"
+
+# IPv4
+if $ENABLE_IP4 && valid_ip4 $IP4; then
+ touch "$IP4FILE"
+
+ if grep -Fxq "$IP4" "$IP4FILE"; then
+ echo "IP is still $IP4. Skipping."
+ else
+ echo "IP4 has changed to $IP4"
+ update_dns $IP4 A && echo "$IP4" > "$IP4FILE"
+ fi
+fi
+
+# IPv6
+if $ENABLE_IP6 && [ -n "$IP6" ]; then
+ touch "$IP6FILE"
+
+ if grep -Fxq "$IP6" "$IP6FILE"; then
+ echo "IP is still $IP6. Skipping."
+ else
+ echo "IP6 has changed to $IP6"
+ update_dns $IP6 AAAA && echo "$IP6" > "$IP6FILE"
+ fi
+fi
+