In this post I will share how I use Cloudflare as Dynamic DNS. I was previously using dynamic DNS service from No-IP for three years until a colleague of mine mentioned about Cloudflare’s really fast global DNS. Initially, I thought that Cloudflare was just a CDN and an Internet company that protects websites from Distributed Denial-of-Service (DDoS) attack, upon further research I found out that Cloudflare also provides a DNS service with a REST-API for you to update your DNS records.

I migrated most of my domain to CloudFlare DNS and then uses their API to update my domain’s DNS records once my ISP changed the IP address.

To know my router’s IP address I use the service of ipinfo.io. You may use other provider or other technique to know your router’s public IP address.

I made this script available on github.com at https://github.com/johnpili/cloudflare-as-dynamic-dns

$nano updateip.sh
#!/bin/bash

IP=$(curl -s "https://ipinfo.io/ip")
echo "THIS IS IP $IP"
touch dynip.txt
OLD_IP=$(cat dynip.txt)
echo "OLD IP: $OLD_IP"

curlUpdate(){
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$1/dns_records/$2" \
-H "X-Auth-Email: [email protected]" -H "X-Auth-Key: YOUR_CLOUDFLARE_API_KEY" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$4\",\"content\":\"$3\",\"proxied\":$5}"
}

if [ "$IP" != "$OLD_IP" ]; then
    echo "Changing IP"
    echo $IP > dynip.txt
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "johnpili.com" "true"
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.johnpili.com" "true"
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "ssh.johnpili.com" "false"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "domain1.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.domain1.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "domain2.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.domain2.com" "true"
fi

You can then setup your CRON to run the script on a specified interval or schedule.

Disclaimer

Cloudflare’s DNS REST API is owned by Cloudflare and subject to Cloudflare’s terms and conditions.