Using AWS Route53 as Dynamic DNS

Basic script I run on my raspberry pi to keep my ISP’s dynamic IP address changes synchronised with my AWS Route53 entry. It uses dig and the AWS CLI tool to resolve the ip address and update route53 entry.

#!/bin/bash
ZONEID=<AWS ZONE ID>
DNSNAME=home.yourdomain.com.au
COMMENT="ip-update"
TTL=300
TYPE=A

BASE=/home/user/ip-update
LOGFILE="$BASE/ip-update.log"

IP=$(dig +short myip.opendns.com @resolver1.opendns.com)
DNSIP=$(dig +short $DNSNAME @ns-1609.awsdns-09.co.uk)
[ -z "$IP" ] && IP=$(curl -s https://api.ipify.org)
echo $(date) >> "$LOGFILE"
echo "Resolved IP: $IP" >> "$LOGFILE"
echo "DNS IP: $DNSIP" >> "$LOGFILE"

if [ "$IP" = "$DNSIP" ]; then
  echo "IP was unchanged." >> "$LOGFILE"
  exit 0
else
  TMPFILE=$(mktemp /tmp/route53-temp.XXXXXXXX)
  cat > ${TMPFILE} << EOF { "Comment":"$COMMENT", "Changes":[{ "Action":"UPSERT", "ResourceRecordSet":{ "ResourceRecords":[{ "Value":"$IP" }], "Name":"$DNSNAME", "Type":"$TYPE", "TTL":$TTL } }] } EOF echo "Updating IP address..." >> "$LOGFILE"
  /usr/local/bin/aws route53 change-resource-record-sets \
    --hosted-zone-id $ZONEID \
    --change-batch file://"$TMPFILE" >> "$LOGFILE"
fi

Leave a Reply