diff --git a/templates/cloudflare-ddns.sh.j2 b/templates/cloudflare-ddns.sh.j2 new file mode 100644 index 0000000..47351e1 --- /dev/null +++ b/templates/cloudflare-ddns.sh.j2 @@ -0,0 +1,88 @@ +#!/bin/bash + +# User variables +domain="{{ cloudflare_ddns_domain }}" +zoneid="{{ cloudflare_ddns_zoneid }}" +apikey="{{ cloudflare_ddns_apikey }}" +ipcheck=ifconfig.io +{% raw %} +# Runtime variables +silent=0 +dns_record_id="" +wanip="" +dnsip="" + +# https://developers.cloudflare.com/api/operations/dns-records-for-a-zone-patch-dns-record + +if [[ "${@}" == "--silent" ]]; then silent=1; fi + +function prereqs() { + prereq=('jq' 'curl' 'tr') + for pre in ${prereq[@]}; do + which $pre >/dev/null + if [ $? -ne 0 ]; then echo "Cannot find required tool $pre in path. Pls install tool or fix path."; exit 1; fi + done + if [ ${#domain} -eq 0 ]; then echo "domain value cannot be blank. Pls fix in script."; exit 1; fi + if [ ${#apikey} -eq 0 ]; then echo "apikey value cannot be blank. Pls fix in script."; exit 1; fi + if [ ${#zoneid} -eq 0 ]; then echo "zoneid value cannot be blank. Pls fix in script."; exit 1; fi + if [ ${#ipcheck} -eq 0 ]; then echo "ipcheck website cannot be blank. Pls fix in script."; exit 1; fi +} + +function getwanip() { + wanip=$(curl -4 https://${ipcheck} 2>/dev/null) +} + +function getdnsip() { + jsondata=$(curl --request GET \ + --url https://api.cloudflare.com/client/v4/zones/${zoneid}/dns_records?name=${domain} \ + --header 'Content-Type: application/json' \ + --header "Authorization: Bearer ${apikey}" 2>/dev/null) + success=$(echo $jsondata | jq '.success') + if [[ "$success" != "true" ]]; then + if [[ $silent -eq 0 ]]; then + echo "Unable to get data for dns record $domain in zone $zoneid. Please see the server response below:" + echo -e "\n${jsondata}\n" + fi + exit 1 + fi + dns_record_id=$(echo $jsondata | jq '.result[0].id' | tr -d \") + dnsip=$(echo $jsondata | jq '.result[0].content' | tr -d \") +} + +function updatedns() { + jsondata=$(curl --request PATCH \ + --url https://api.cloudflare.com/client/v4/zones/${zoneid}/dns_records/${dns_record_id} \ + --header 'Content-Type: application/json' \ + --header "Authorization: Bearer ${apikey}" \ + --data "{ + 'content': '${wanip}', + 'name': '${domain}', + 'type': 'A' + }" 2>/dev/null) + success=$(echo $jsondata | jq '.success') + if [[ "$success" != "true" ]]; then + if [[ $silent -eq 0 ]]; then + echo "Unable to update data for dns record $domain in zone $zoneid. Please see the server response below:" + echo -e "\n${jsondata}\n" + fi + exit 1 + fi +} + +prereqs +getwanip +getdnsip + +if [[ "${wanip}" == "${dnsip}" ]]; then + if [ $silent -eq 0 ]; then + echo "WAN IP and DNS IP are the same. Not changing. (W:${wanip} / D:${dnsip})" + fi + exit 0 +else + if [ $silent -eq 0 ]; then + echo "WAN IP and DNS IP do not match. Updating DNS IP. (W:${wanip} / D:${dnsip})" + fi + updatedns + exit 0 +fi +{% endraw %}