Post

Cloudflare DDNS Updater via Shell Script

Cloudflare DDNS Updater via Shell Script

Keep your Cloudflare DNS records up to date with your current external IP via a shell script.

Reference: Cloudflare DDNS on Linux

Prerequisites

1
apt install jq curl

Create the Script

1
nano /usr/local/bin/ddns

Use the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash

# Check for current external IP
IP=`dig +short txt ch whoami.cloudflare @1.0.0.1| tr -d '"'`

# Set Cloudflare API
URL="https://api.cloudflare.com/client/v4/zones/DNS_ZONE_ID/dns_records/DNS_ENTRY_ID"
TOKEN="YOUR_TOKEN_HERE"
NAME="DNS_ENTRY_NAME"

# Connect to Cloudflare
cf() {
  curl -X ${1} "${URL}" \
       -H "Content-Type: application/json" \
       -H "Authorization: Bearer ${TOKEN}" \
       ${2} ${3}
}

# Get current DNS data
RESULT=$(cf GET)
IP_CF=$(jq -r '.result.content' <<< ${RESULT})

# Compare IPs
if [ "$IP" = "$IP_CF" ]; then
    echo "No change."
else
    RESULT=$(cf PUT --data "{\"type\":\"A\",\"name\":\"${NAME}\",\"content\":\"${IP}\"}")
    echo "DNS updated."
fi

Replace the placeholders:

VariableWhere to find
DNS_ZONE_IDZone ID in the Cloudflare domain dashboard
DNS_ENTRY_IDGet from Cloudflare API — List DNS Records
YOUR_TOKEN_HERECreate an API token with Zone.Edit permission

To get the DNS entry ID via API:

1
2
3
4
curl --request GET \
  --url https://api.cloudflare.com/client/v4/zones/zone_id/dns_records \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer YOUR_TOKEN_HERE'

Setup

Make the script executable:

1
chmod 755 /usr/local/bin/ddns

Edit crontab to run every minute:

1
crontab -e

Add:

1
* * * * * /usr/local/bin/ddns > /dev/null 2>&1

Done.

This post is licensed under CC BY 4.0 by the author.