Skip to content

Instantly share code, notes, and snippets.

@gonzaleztroyano
Created January 3, 2022 02:43
Show Gist options
  • Save gonzaleztroyano/d86210915347f1c9ec1ceb940a5ade0c to your computer and use it in GitHub Desktop.
Save gonzaleztroyano/d86210915347f1c9ec1ceb940a5ade0c to your computer and use it in GitHub Desktop.
Bash Script to dynamically update a DNS record (DDNS) using Cloudflare API
#!/bin/bash
# This script is made to programmatically update a DNS record managed on Cloudflare via its API.
# CC BY 4.0 Pablo González Troyano - 2022
# The script is provided “AS IS” Without warranty of any kind. // Based on cloudflare-ddns-update.sh by Trash2.
# CF API Documentation: https://api.cloudflare.com/
# Update the following variables as needed.
zone=example.com
zone_id=023e105f4ecef8ad9ca31a8372d0c353 # Just example data, replace with your Zone ID
record=sub.example.com # Incluiding base domain
record_id=372e67954025e0ba6aaa6d586b9e0b59 # See below - Just example data, replace with your own.
cloudflare_token=c2547eb745079dac93203cc5cfdda41 # See https://dash.cloudflare.com/profile/api-tokens
logfile="/home/user/cf-updater.log" # Full/Absolute path
# Get your record ID and save in the "record_id" variable. You can get it using:
# curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?type=A&name=${record}" \
# -H "Authorization: Bearer ${cloudflare_token}" \
# -H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id'
# Once updated the variables and tested (super important) just add a crontab (using "crontab -e").
# For example, every 15 minutes:
# */15 * * * * /bin/bash <PATH-TO-SCRIPT>
# Create (if needed) the log file, and redirect output
if [ ! -f "$logfile" ]; then
touch ${logfile}
fi
# Get and save current IP & current record value
curr_ip=$(curl -s -X GET https://checkip.amazonaws.com)
curr_reg=$(dig ${record} +short @1.1.1.1)
# If curr_ip = record IP, do nothing. Else, update.
if echo ${curr_reg} | grep ${curr_ip}; then
echo "$(date --rfc-3339=seconds) - OK - Current record matches current IP (${curr_ip})" >> ${logfile}
else
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${record_id}" \
-H "Authorization: Bearer ${cloudflare_token}" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"${record}\",\"content\":\"$curr_ip\",\"ttl\":1,\"proxied\":false}" > /dev/null
echo "$(date --rfc-3339=seconds) - NOK - Record Updated to $curr_ip from ${curr_reg}" >> ${logfile}
fi
# End
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment