DEV Community

Adam Mateusz Brożyński
Adam Mateusz Brożyński

Posted on

3 1

Cloudflare DDNS on Linux

1. Generate token in My profile → API Tokens → Create Token with Zone.DNS permission for selected DNS zone.*

Note that it is not possible to select only one subdomain and token will have permission to change all DNS entries.

2. Use the following script to update DNS entry automatically on your server and save it as /usr/local/bin/ddns:

#!/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
Enter fullscreen mode Exit fullscreen mode

3. Add script to crontab, so it will be executed every minute:

# crontab -e
Enter fullscreen mode Exit fullscreen mode
* * * * * /usr/local/bin/ddns > /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (1)

Collapse
 
nadalizadeh profile image
Ali N.

Would you please clarify where the DNS_ENTRY_ID parameter should be filled from?

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay