summaryrefslogtreecommitdiff
path: root/hetzner-ddns.sh
diff options
context:
space:
mode:
authorDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2023-03-14 01:23:11 -0700
committerDavid Vazgenovich Shakaryan <dvshakaryan@gmail.com>2023-03-14 01:23:11 -0700
commitd62a63c3841d3ef005bbf1494c7cdbfa7c25863f (patch)
treec111e52c4b400132decbc23794d7b99504d7dda2 /hetzner-ddns.sh
parent3e2bb49efc35039d9510ea0f9d11b5446b53c923 (diff)
downloadhetzner-ddns-d62a63c3841d3ef005bbf1494c7cdbfa7c25863f.tar.gz
hetzner-ddns-d62a63c3841d3ef005bbf1494c7cdbfa7c25863f.tar.xz
update for Hetzner instead of Linode
Diffstat (limited to 'hetzner-ddns.sh')
-rwxr-xr-xhetzner-ddns.sh59
1 files changed, 59 insertions, 0 deletions
diff --git a/hetzner-ddns.sh b/hetzner-ddns.sh
new file mode 100755
index 0000000..7ad8e28
--- /dev/null
+++ b/hetzner-ddns.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+#
+# Copyright 2022 David Vazgenovich Shakaryan
+#
+# HETZNER_TOKEN=<token> hetzner-ddns.sh <domain>
+
+IP_RESOLVER='https://ifconfig.co'
+TARGET="${1}"
+
+shopt -s extglob
+
+die() {
+ [[ -n "${@}" ]] && echo "${@}" >&2
+ exit 1
+}
+
+hetzcurl() {
+ curl -sfH "Auth-API-Token: ${HETZNER_TOKEN}" \
+ "https://dns.hetzner.com/api/v1/${1}" \
+ "${@:2}"
+}
+
+ip="$(curl -sf4 "${IP_RESOLVER}")" || die 'IP lookup failed'
+
+zone_re="${TARGET}"
+while [[ "${zone_re}" =~ ^([^\\]*)\.(.*)$ ]]; do
+ zone_re="(${BASH_REMATCH[1]}\\.)?${BASH_REMATCH[2]}"
+done
+
+res="$(hetzcurl "zones")" || die 'Zones lookup failed'
+IFS='|' read zone_id zone_name < <(jq -er --arg re "${zone_re}" \
+ '[.zones[] | select(.name | test("\\A" + $re + "\\z"))] |
+ if . == [] then (null | halt_error) else . end |
+ max_by(.name | length) | [.id, .name] | join("|")' \
+ <<< "${res}") || die 'Zone not found'
+rec_name="${TARGET%%?(.)${zone_name}}"
+rec_name="${rec_name:-@}"
+
+res="$(hetzcurl "records?zone_id=${zone_id}")" || die 'Records lookup failed'
+rec_id="$(jq -er --arg name "${rec_name}" \
+ 'first(.records[] | select(.type == "A" and .name == $name)) | .id' \
+ <<< "${res}")" || die 'Record not found'
+
+res="$(hetzcurl "records/${rec_id}")" || die 'Record lookup failed'
+old_ip="$(jq -r '.record.value' <<< "${res}")"
+
+if [[ "${old_ip}" == "${ip}" ]]; then
+ echo "IP unchanged from ${ip}"
+ exit
+fi
+
+data="$(jq -c --arg ip "${ip}" \
+ '.record | {zone_id, type, name, value: $ip }' <<< "${res}")"
+res="$(hetzcurl "records/${rec_id}" \
+ -H 'Content-Type: application/json' \
+ -X PUT -d "${data}")" || die 'Record update failed'
+new_ip="$(jq -r '.record.value' <<< "${res}")"
+
+echo "IP changed from ${old_ip} to ${new_ip}"