Dynamic DNS with the Linode CLI

I've posted an improved method here here

For a while I've been looking for an elegant (and free) solution to mapping a custom DNS record for domains I own to the dynamic IP address of my ADSL connection, mainly for convenient remote access when traveling. I use Linode for my web hosting and DNS so it seemed logical to try and find a solution there. Today when Linode released their new CLI tool it provided me with the inspiration I needed.

In this post I'll show how I wrote a bash script to get my external IP address and update the Linode DNS A record pointing to my home network.

Getting the IP

As the external IP address of most ASDL connections is not the same one mapped to the machine you'll be running this script from an external service is required. A quick Google search reveals many APIs which simply echo back the IP address from which the request came, this saves parsing a page like whatismyip. A list is available here. Curl can then be used to get this address into the script.

Updating the DNS

Most decent DNS hosting services have an API from which DNS records can be modified. Linode have a conventional HTTP API, but the new CLI tool makes it even easier to work with. The API / CLI tools can view and modify most settings of your VMs but in this case the command to update an A record named lan is:

linode domain record-update -l oliversmith.io -t A -m lan -T 5 -R 1.1.1.1

This command looks for the lan A record of oliversmith.io and updates the IP it points to, to 1.1.1.1 with a TTL of 5 minutes. A low TTL will stop DNS servers caching an incorrect IP address for more than 5 minutes. Full API documentation can be found on the Linode Github

Note: I thought it best to manually configure the A record first then update from there, creation is slightly different

Code

These two simple tools can be combined together into a bash script. This can then be set to run periodically as a cron job.

#!/bin/bash

# Get the IP address from anywhere that will echo it
ip=`curl -s http://ipecho.net/plain`
echo "Your current IP Address is: "$ip

linode domain record-update -l oliversmith.io -t A -m lan -T 5 -R $ip

It's a good idea to be respectful to the nice people who provide these free services and poll only a few times an hour, not every second! If you require more frequent updates it'd be easy to add a script on a web server to show you the current external IP.