Skip to content

Instantly share code, notes, and snippets.

@NKID00
Last active September 10, 2025 02:48
Show Gist options
  • Select an option

  • Save NKID00/8dac3004f3a3af33713258442c93f874 to your computer and use it in GitHub Desktop.

Select an option

Save NKID00/8dac3004f3a3af33713258442c93f874 to your computer and use it in GitHub Desktop.
Bash Script to Update Cloudflare DNS Record upon IP Address Change
#!/bin/bash
# This script by NKID00 is marked CC0 1.0.
set -e
# To query dns record id:
# curl https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records \
# -H "Authorization: Bearer $API_TOKEN"
ZONE_ID=1
DNS_RECORD_ID=2
API_TOKEN=3
DOMAIN=4
DEVICE=5
function query_ip_address() {
addr="$(
ip -6 -j addr show dev $DEVICE scope global primary -tentative up \
| jq -r '(.[0] // empty).addr_info | sort_by(.prefixlen) | map(.local // empty)[0] // empty'
)"
if [ -z "$addr" -o "$addr" = "$previous" ]; then
return 1
fi
previous="$addr"
return 0
}
function update_record() {
printf -- "IP addr is now [$addr], updating... "
comment="Updated on $(date -Is)"
export DOMAIN addr comment
jq -n '{name: env.DOMAIN, content: env.addr, comment: env.comment, ttl: 60, type: "AAAA", proxied: false}' \
| curl https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$DNS_RECORD_ID \
-s -X PUT -H "Authorization: Bearer $API_TOKEN" --json @- \
| jq -r 'if .success then "OK" else ("Error", .) end'
}
query_ip_address && update_record
ip -6 mon addr dev $DEVICE | while true; do
read -r -t 3600 # Force recheck after timeout
query_ip_address && update_record
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment