Skip to content

Instantly share code, notes, and snippets.

@mattrude
Last active September 5, 2020 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattrude/4d452462b01901573775df9ac5bc831d to your computer and use it in GitHub Desktop.
Save mattrude/4d452462b01901573775df9ac5bc831d to your computer and use it in GitHub Desktop.
Cloudflare Zone Updater
#!/bin/bash
Host="lora"
Domain="theodin.network"
User="<--Cloudflare-Username-->"
Key="<--Cloudflare-API-Key-->"
###############################################################################################
Missing=''
if [ ! -x /usr/bin/jq ]; then
Missing="${Missing} jq"
fi
if [ ! -x /usr/bin/dig ]; then
Missing="${Missing} dnsutils"
fi
if [ `echo ${Missing} |wc -w` -gt 0 ]; then
echo "Missing:${Missing}"
sudo apt update; sudo apt -y install ${Missing}
fi
###############################################################################################
LocalIP=`curl -sL "https://checkip.amazonaws.com"`
DNSIP=`dig ${Host}.${Domain} @1.1.1.1 @1.0.0.1 +short`
if [ "${DNSIP}" != "${LocalIP}" ]; then
ZoneID=`curl -sX GET "https://api.cloudflare.com/client/v4/zones" -H "X-Auth-Email: ${User}" -H "X-Auth-Key: ${Key}" \
-H "Content-Type: application/json" |jq ".result | .[] | select(.name == \"${Domain}\" ) .id" |sed 's/"//g'`
RemoteIP=`curl -sX GET "https://api.cloudflare.com/client/v4/zones/${ZoneID}/dns_records" -H "X-Auth-Email: ${User}" \
-H "X-Auth-Key: ${Key}" -H "Content-Type: application/json" \
|jq ".result | .[] | select(.name == \"${Host}.${Domain}\" ).content" |sed 's/"//g'`
if [ "${RemoteIP}" != "${LocalIP}" ]; then
HostID=`curl -sX GET "https://api.cloudflare.com/client/v4/zones/${ZoneID}/dns_records" -H "X-Auth-Email: ${User}" \
-H "X-Auth-Key: ${Key}" -H "Content-Type: application/json" \
|jq ".result | .[] | select(.name == \"${Host}.${Domain}\" ) .id" |sed 's/"//g'`
Data="{\"type\":\"A\",\"name\":\"${Host}.${Domain}\",\"content\":\"${LocalIP}\",\"ttl\":120,\"proxied\":false}"
Output=`curl -sL -X PUT "https://api.cloudflare.com/client/v4/zones/${ZoneID}/dns_records/${HostID}" \
-H "X-Auth-Email: ${User}" -H "X-Auth-Key: ${Key}" -H "Content-Type: application/json" --data ${Data}`
TEST=`echo ${Output} |jq -c '{success} | .[]'`
if [ "${TEST}" == "true" ]; then
echo "DNS record for ${Host}.${Domain} has been updated from ${RemoteIP} to ${LocalIP}!"
else
echo "DNS update failed"
echo "The DNS record to be updated was ${Host}.${Domain}."
echo "Tried to change the address form ${RemoteIP} to ${LocalIP}!"
echo -n "The error message is: "
echo ${Output} |jq '.errors |.[] .message'
fi
else
echo "The DNS IP address (${DNSIP}) dose not match the remote IP address (${RemoteIP}) or the local IP Address (${LocalIP})"
echo "This was most likly caused if we just updated the record but the DNS server hasn't updated yet"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment