Question/Problem

How can I use Amazon Web Services (AWS) Route53 DNS service to provide dynamic DNS updates from my Linux machine? For years I used a dynamic DNS service that charged me annually to update domains dynamically with a client.

Solution

Bring AWS Route53 into the picture, and it’s a no brainer to do everything in there.

Requirements

For this to work, you will need to install the aws cli tools.

You will also need the bind-utils package.

Once the aws cli tools have been installed and configured, you can move onto the next phase.

Script

#!/bin/bash

ZONEID="<ZONEID>"
RECORDSET="<Full Hostname you're updating>"
TTL=300
COMMENT="Auto updating @ `date`"
IP4=`dig -4 +short myip.opendns.com @resolver1.opendns.com`
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
LOGFILE="$DIR/update-route53.log"
IPFILE="$DIR/update-route53.ip"

if [ ! -f "$IPFILE" ]
    then
    touch "$IPFILE"
fi

if grep -Fxq "IP4: $IP4" "$IPFILE"; then
    echo "IP is still $IP4. Exiting" >> "$LOGFILE"
    exit 0
else
    echo "IP has changed to $IP4 and $IP6" >> "$LOGFILE"
    TMPFILE=$(mktemp /tmp/temporary-file.XXXXXXXX)
    cat > ${TMPFILE} << EOF
    {
      "Comment":"$COMMENT",
      "Changes":[
        {
          "Action":"UPSERT",
          "ResourceRecordSet":{
            "ResourceRecords":[
              {
                "Value":"$IP4"
              }
            ],
            "Name":"$RECORDSET",
            "Type":"A",
            "TTL":$TTL
          }
        }
      ]
    }
EOF

aws route53 change-resource-record-sets \
    --hosted-zone-id $ZONEID \
    --change-batch file://"$TMPFILE" >> "$LOGFILE"
    echo "" >> "$LOGFILE"
    rm $TMPFILE
        printf "IP4: $IP4" > "$IPFILE"
fi

You will want to edit the first 2 values in this script.

  1. ZoneID. You can get the Zone ID by going to the Hosted Zones page in the AWS console.
  2. Record Name to update. This needs to be the fully qualified domain name, like computer.domain.tld.

Setup script and crontab

After you’ve setup the script in a path such as /root/dynamicdns.sh, make sure to chmod u+x /root/dynamicdns.sh to make it executable.

I set mine to run in a crontab every 30 minutes.

*/30 * * * * /root/dynamicdns.sh >/dev/null 2>&1