How to script your own dynamic DNS on CentOS with Linode API

28 Apr 2012 by rayheffer

You know the story… you don’t have a static IP address for your internet connection so you use dynamic DNS, except a certain dynamic DNS company are no longer offering this for free. Well, an alternative is to script this yourself with a single line of code on your own Linux box at home and get it to update your DNS for you. You can have home.yourdomain.com update with your home internet IP automatically! I use Linode to provide me with my Linux web server, which runs on CentOS 6.2, but the other great thing about Linode is that you can use their name servers and have full access to your zone files. Even better still, they provide an API to do this and it’s really easy to set up. What you need:

  1. A Linux machine (or Apple Mac) at home – This can either be a virtual machine running on your home PC or lab server, Ubuntu on your PC, laptop or you can even do this on your Apple Mac!
  2. A domain name hosted on Linode DNS servers.
  3. API key from Linode (Log into Linode then go to ‘my profile’ and scroll down to API key)
  4. A chair to sit on whilst you write some awesome bash scripts.

The Script

#!/bin/sh
API_KEY=<API_KEY>
DOMAIN_ID=<DOMAIN_ID>
RESOURCE_ID=<RESOURCE_ID>
wget -qO- https://api.linode.com/?api_key="$API_KEY"\&api_action=domain.resource.update\&DomainID="$DOMAIN_ID"\&ResourceID="$RESOURCE_ID"\&Target=[remote_addr]

You’ll need to replace the sections in <> as follows:

<API_KEY> – This is the API Key that you can obtain from the ‘my profile’ page on your Linode account.

<DOMAIN_ID> – To obtain this, login into Linode and click on DNS Manager. Click on the ‘zone file’ for the domain and the ID is in square brackets at the top of the zone file (I.e ; yourdomain.com [17546])

<RESOURCE_ID> – Log in to Linode, go to DNS Manager and edit the domain zone that you wish to update. Now edit the host record (I.e. home) and you’ll see the URL is something similar to: https://manager.linode.com/dns/resource/yourdomain.com?id=723215. The ID number (723215) is your Resource ID. The wget line will call the API function and [remote_addr] will simply update it with the IP address the request is coming from (in other words, your home internet connection). If you want to get a bit more clever with your script, you could create an IF statement to check the IP address it has with your existing one. If they are different then update it, otherwise exit the script. Automating the DNS Update:

The final step is to schedule this script to run every few hours. I use crontab for this, and it looks something like this:

0 */4 * * * /home/.scripts/linode-dns.sh 2>&1

That’s it!

Comments are closed for this post.