Skip to content

Instantly share code, notes, and snippets.

@nothub
Last active February 1, 2025 12:12
Show Gist options
  • Save nothub/8bf947beba628abfea58b1574433a164 to your computer and use it in GitHub Desktop.
Save nothub/8bf947beba628abfea58b1574433a164 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Required API token permissions are "Zone:Read" and "DNS:Edit".
# Cronjob example:
# */15 * * * * { date --iso-8601=seconds; API_TOKEN=<token> /usr/local/bin/cfddns -z <id> -r <id>; printf "\n"; } >> cfddns.log 2>&1
usage="Usage: API_TOKEN=<token> cfddns -z <id> -r <id>"
set -o errexit
set -o pipefail
while getopts z:r:t: opt; do
case $opt in
z) zone_id="${OPTARG}" ;;
r) record_id="${OPTARG}" ;;
*)
echo >&2 "${usage}"
exit 1
;;
esac
done
shift $((OPTIND - 1))
if test -z "${API_TOKEN}" || test -z "${zone_id}" || test -z "${record_id}"; then
echo >&2 "${usage}"
exit 1
fi
set -o nounset
ip="$(curl -4fsSL 'https://cloudflare.com/cdn-cgi/trace' | grep -Phoi '^ip=.+$' | awk -F= '{print $2}')"
echo "${ip}"
if ! echo "${ip}" | grep -P '^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$' > /dev/null; then
echo >&2 "invalid ipv4 😠"
exit 1
fi
response="$(
curl -sSL \
-X PUT \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer ${API_TOKEN}" \
-d "$(printf '{"type":"A","name":"@","content":"%s"}' "${ip}")" \
"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${record_id}"
)"
if test "$(echo "${response}" | jq -r '.success')" = "true"; then
echo >&2 "record updated 🎉"
else
echo >&2 "update failed 😠"
errors="$(echo "${response}" | jq -r '.errors[]')"
if test -n "${errors}"; then
echo >&2 "${errors}"
fi
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment