Dynamically update Cloudflare DNS records using the web API

No global API key required

Posted by Valentin Heidelberger on Tuesday, November 12, 2019 Tags: RaspberryPi Technology Linux   2 minute read

Why

I’m using Cloudflare as a CDN and DNS provider. For a system with an external IPv4 address that changes daily, I needed a dynamically updated DNS record. There are numerous ways to do DynDNS but I wanted to get into Cloudflare’s API anyway and it turns out that this is, at least in my opinion, much easier to set up than some generic DynDNS package.

How

Getting the script

I’ve forked a script by benkulbertis. The fork does not require a general API token. So you can set up API tokens specifically authorized for what the script needs to do. You can get the script here.

Setting up API tokens

Next, you need to set up the required tokens. The script needs two tokens: one to read DNS records and settings and one to actually edit a DNS zone. To set the tokens up, log in to your Cloudflare account, go to this page and click Create Token. Note, that you can also limit the tokens to a specific domain! This is of course important to know if you have multiple domains in your Cloudflare account and the script shall only read/edit the settings of one of these. You can give your token a custom name and then have to select the permissions it’s supposed to have. These are as follows:

Read token

Type Resource Permission
Account Access: Organizations, Identity Providers, Groups Read
Zone Zone Settings Read
Zone DNS Read

Edit token

Type Resource Permission
Zone DNS Edit

Configuring the script

Now, that you’ve successfully created the API tokens, configure the script by modifying the first four variables accordingly.

Variable Value
read_token The read token you’ve just created
edit_token The edit token you’ve just created
zone_name The DNS zone your record lies in (e.g. example.com)
record_name The DNS record (e.g. mysubdomain.example.com)

Moving on

I’ll probably rewrite the script in Python and add an argument parser soon. If you have any other ideas, feel free to drop them here as an issue or pull request.