Logo

Armand.nz

Home / About / Linkedin / Github

Update CloudFlare dynamic DNS

#DDNS #DNS #CloudFlare |

#!/bin/bash

# A bash script to update a Cloudflare DNS A record with the external IP of the source machine
# Used to provide DDNS service for my home
# Needs the DNS record pre-creating on Cloudflare
# You can place in /usr/local/bin/cloudflare-update-record-example.com.sh
# Required: jq and curl: apt-get install jq curl

# Then Add script as cronjob
## Cron jobs for the server running dynamic DNS updates
## Dynamic cloudflare DNS 0 armsultan.com
# 0 * * * * /usr/local/bin/cloudflare-update-record-example.com.sh

## Based on https://gist.github.com/Tras2/cba88201b17d765ec065ccbedfb16d9a with updates to use
## per-zone configurable access tokens available in the API sections of your Cloudflare profile

# Proxy - uncomment and provide details if using a proxy
#export https_proxy=http://<proxyuser>:<proxypassword>@<proxyip>:<proxyport>

# Cloudflare zone is the zone which holds the record
dnsrecord=t3st.org
zoneid=xxxxxxxxxxxxxxxxxxx #locate on cloudflare dashboard (unique per domain)

## Cloudflare authentication details
## keep these private
## authkey created through new api token > Permissions: DNS (Edit) > 
## Zone Resources: include All Zones or just one zone
## confirm token by running:
## curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
##     -H "Authorization: Bearer Q-mytokenxxxxxxxxxxxx" \
##     -H "Content-Type:application/json"
cloudflare_auth_key=Q-mytokenxxxxxxxxxxxx

# Get the current external IP address
ip=$(curl -s -X GET https://checkip.amazonaws.com)

#echo "Current IP is $ip"

if host $dnsrecord 1.1.1.1 | grep "has address" | grep "$ip"; then
#  echo "$dnsrecord is currently set to $ip; no changes needed"
  exit
fi

# if here, the dns record needs updating

# get the dns record id
dnsrecordid=$(curl -v -s -X GET "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records?type=A&name=$dnsrecord" \
  -H "Authorization: Bearer $cloudflare_auth_key" \
  -H "Content-Type: application/json" | jq -r  '{"result"}[] | .[0] | .id')

# update the record
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zoneid/dns_records/$dnsrecordid" \
  -H "Authorization: Bearer $cloudflare_auth_key" \
  -H "Content-Type: application/json" \
  --data "{\"type\":\"A\",\"name\":\"$dnsrecord\",\"content\":\"$ip\",\"ttl\":1,\"proxied\":false}" | jq

comments powered byDisqus

Copyright © Armand