DDNS with Linode and a Linux machine

Posted: | Updated: | Tags: aws cloud linux til

This post details how to update a domain record entry on Linode based on the public IP of a machine running Linux. We will create a python script and use the Linode API to accomplish this.

Create a personal token in Linode

From your Linode console under My Profile > API Tokens you can create a personal access token. The script only requires read/write access to the Domains scope. From here you can also set your desired expiration time.

Copy the token, we’ll need it in the next step.

Create the following files on the machine

Create a directory with two files, .env and update_dns.py.

Open .env and paste the following lines.

# .env

# The personal token created previously
linode_token=
# The domain entry in Linode (i.e. pesky.moe)
domain=
# The A/AAA  domain record (i.e. blog) 
record=

Next, open update_dns.py and insert the following lines.

# update_dns.py
from linode_api4 import LinodeClient
import requests
import os
from dotenv import load_dotenv

load_dotenv()

ip = requests.get('https://checkip.amazonaws.com').text.strip()
token = os.getenv('linode_token')

client = LinodeClient(token)

domains = client.domains()
for current_domain in domains:
    if current_domain.domain == os.getenv('domain'):
        for record in current_domain.records:
            if record.name == os.getenv('record'):
                record.target = ip
                record.save()
                print(record.name, record.target, record.type)

Run on startup

One way to run the script on startup is using crontab. Edit crontab:

crontab -e

Add the following line at the end.

@reboot python /path/to/script/update_dns.py &

Related ramblings