Skip to content

Instantly share code, notes, and snippets.

@toriato
Last active September 14, 2021 02:09
Show Gist options
  • Save toriato/98b5b070d4bb355153afd8110fa2f2dc to your computer and use it in GitHub Desktop.
Save toriato/98b5b070d4bb355153afd8110fa2f2dc to your computer and use it in GitHub Desktop.
Cloudflare DDNS bash script
#!/bin/bash
# cloudflare-ddns.sh
# requires bash, jq and curl to run!
# TODO: error handling :)
# token can be generate from https://dash.cloudflare.com/profile/api-tokens
# requires Zone.DNS permission to update DNS record
# more info on https://api.cloudflare.com/#getting-started-requests
TOKEN="__________"
DNS=(
"example.com"
"hello.example.com"
"my.example.net"
)
ENDPOINT="https://api.cloudflare.com/client/v4"
remoteIP=$(curl -sSX GET "https://api.ipify.org")
echo "Current remote IP address is $remoteIP"
zones=$(curl -sSX GET "$ENDPOINT/zones" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json")
for (( i = 0; i < $(jq ".result | length" <<< $zones); i++ )); do
zone=$(jq ".result[$i]" <<< $zones)
zoneID=$(jq -r ".id" <<< $zone)
records=$(curl -sSX GET "$ENDPOINT/zones/$zoneID/dns_records" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json")
for (( j = 0; j < $(jq ".result | length" <<< $records); j++ )); do
record=$(jq ".result[$j]" <<< $records)
recordID=$(jq -r .id <<< $record)
recordName=$(jq -r ".name" <<< $record)
recordType=$(jq -r .type <<< $record)
recordTTL=$(jq -r .ttl <<< $record)
if [[ "${DNS[*]}" =~ "$recordName" ]]; then
if [[ "$remoteIP" == "$(jq -r ".content" <<< $record)" ]]; then
echo "Skipping $recordType record with '$recordName' name"
continue
fi
echo "Updating $recordType record with '$recordName' name"
curl -sSX PUT "$ENDPOINT/zones/$zoneID/dns_records/$recordID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json; charset=utf-8" \
-d "{\"content\":\"$remoteIP\",\"type\":\"$recordType\",\"ttl\":$recordTTL}"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment