Dynamic DNS with CloudFlare

· 2 min read

Here’s a simple bash script to keep your DDNS updated:

#!/usr/bin/env bash
# Create this in the CF UI
API_TOKEN=**********************************
# This is visible on the CF UI in the Overview section for each domain
ZONE_ID=**********************************
# Uncomment this only while discovering your RECORD_ID with it
#curl -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
#     -H "Authorization: Bearer ${API_TOKEN}" \
#     -H "Content-Type:application/json"
RECORD_ID=**********************************
MY_IP="$(dig +short myip.opendns.com @resolver1.opendns.com)"
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${RECORD_ID}" \
     -H "Authorization: Bearer ${API_TOKEN}" \
     -H "Content-Type: application/json" \
     --data '{"content":"${MY_IP}"}'

EDIT: Here’s a more involved solution for people that care for their uptime:

#!/usr/bin/env bash
# Create this in the CF UI
API_TOKEN=**********************************
# This is visible on the CF UI in the Overview section for each domain
ZONE_ID=**********************************
# Uncomment this only while discovering your RECORD_ID with it
#curl -X GET "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records" \
#     -H "Authorization: Bearer ${API_TOKEN}" \
#     -H "Content-Type:application/json"
RECORD_ID=**********************************
LAST_IP=""
updateCloudFlare() {
    echo "Setting DDNS IP to: ${MY_IP}"
    curl --silent -X PATCH "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${RECORD_ID}" \
        -H "Authorization: Bearer ${API_TOKEN}" \
        -H "Content-Type: application/json" \
        --data '{"content":"${MY_IP}"}' > /dev/null
    if [ $? -eq 0 ]; then
        echo "Success"
    else
        echo "Failed"
    fi
}
while :
do
    echo "Checking public IP..."
    MY_IP="$(curl --silent ifconfig.me)"
    if [ "${MY_IP}" != "${LAST_IP}" ]; then
        LAST_IP=${MY_IP}
        echo "Detected public IP change"
        updateCloudFlare
    else
        echo "IP remained the same"
    fi
    echo "Sleeping a minute..."
 sleep 60
done

Stable Diffusion thinks this image is somehow related to Dynamic DNS

Have fun,

Adrian

Originally published on Medium, 6 November 2022. Original.

#cloudflare #dynamic-dns