Skip to content

Instantly share code, notes, and snippets.

@mortie
Created September 13, 2022 19:22
Show Gist options
  • Save mortie/6ad2c9df317b13a186cc180869497b55 to your computer and use it in GitHub Desktop.
Save mortie/6ad2c9df317b13a186cc180869497b55 to your computer and use it in GitHub Desktop.
Cloudflare dynamic DNS
#!/bin/sh
set -eu
token='<your API token>'
zone='<your DNS zone ID>'
record='<your DNS record ID>'
ip_url='ifconfig.co'
call() {
url="$1"
shift
json="$(curl --silent \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
"$@" "https://api.cloudflare.com/client/v4/$url")"
if [ "$(echo "$json" | jq .success)" != "true" ]; then
echo "API request ($* $url) failed:" >&2
echo "$json" | jq .errors >&2
exit 1
fi
echo "$json"
}
dns_ip="$(call "zones/$zone/dns_records/$record" | jq -r .result.content)"
current_ip="$(curl --silent "$ip_url")"
if [ "$dns_ip" = "$current_ip" ]; then
echo "DNS IP address up to date ($dns_ip). Nothing to do."
exit 0
fi
echo "IP address changed: '$dns_ip' -> '$current_ip'. Updating..."
template='{"type": "A", "name": "serve.mort.coffee", "content": $ip, "ttl": 1}'
call "zones/$zone/dns_records/$record" -X PUT \
--data "$(jq --null-input --arg ip "$current_ip" "$template")" >/dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment