Skip to content

Instantly share code, notes, and snippets.

@Kalvisan
Forked from lifehome/README.md
Last active July 31, 2018 11:28
Show Gist options
  • Save Kalvisan/974c6643da5ade4d716a3e81130ed24b to your computer and use it in GitHub Desktop.
Save Kalvisan/974c6643da5ade4d716a3e81130ed24b to your computer and use it in GitHub Desktop.
Cloudflare API v4 Dynamic DNS Update in Bash

Cloudflare DDNS bash client with systemd

This is a bash script to act as a Cloudflare DDNS client, useful replacement for ddclient.

How to use?

  1. Put the ddns.sh files to /root/
  2. chmod +x /root/ddns.sh
  3. Now you need to execute your script somehow: 4.1) Add script to CRONTAB job, to execute it every 1 hour.
  • At the end of file /etc/crontab add line: * */1 * * * root bash /root/ssh.sh 4.2) Or use /etc/rc.local file, who will execute script on startup
#!/bin/bash
# Forked by lifehome/README.md
# CHANGE THESE
auth_email="[email protected]" # The email used to login 'https://dash.cloudflare.com'
auth_key="fffffffffffffffffffffffffffffffffffff" # Top right corner, "My profile" > "Global API Key"
zone_identifier="ffffffffffffffffffffffffffffffff" # Can be found in the "Overview" tab of your domain
record_name="domain.example.com" # Which record you want to be synced
# DO NOT CHANGE LINES BELOW
ip=$(curl -s https://v4.ifconfig.co/ip)
# SCRIPT START
echo "[Cloudflare DDNS] Check Initiated" | systemd-cat
# Seek for the record
record=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records?name=$record_name" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json")
# Can't do anything without the record
if [ $record == *"\"count\":0"* ]; then
echo -e "Record does not exist, perhaps create one first?" | systemd-cat -p emerg
exit 1
fi
# Set existing IP address from the fetched record
old_ip=$(echo "$record" | grep -Po '(?<="content":")[^"]*' | head -1)
# Compare if they're the same
if [ $ip == $old_ip ]; then
echo "IP has not changed."
exit 0
fi
# Set the record identifier from result
record_identifier=$(echo "$record" | grep -Po '(?<="id":")[^"]*' | head -1)
# The execution of update
update=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records/$record_identifier" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" --data "{\"id\":\"$zone_identifier\",\"type\":\"A\",\"name\":\"$record_name\",\"content\":\"$ip\"}")
# The moment of truth
case "$update" in
*"\"success\":false"*)
echo -e "[Cloudflare DDNS] Update failed for $record_identifier. DUMPING RESULTS:\n$update" | systemd-cat -p emerg
exit 1;;
*)
echo "[Cloudflare DDNS] IP synced to: $ip" | systemd-cat;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment