|
#!/usr/bin/env bash |
|
|
|
# ------------------------------------------------------- |
|
# A shell script that auto update VPS IP to Hetzner DNS |
|
# Written by: @ookangzheng |
|
# Last updated on: 2022/06/26 |
|
# Licensed under the Apache License, Version 2.0 (the "License") http://www.apache.org/licenses/LICENSE-2.0; |
|
# ------------------------------------------------------- |
|
|
|
# Debug |
|
# set -ex |
|
|
|
API_TOKEN="<TOKEN>" |
|
IP="" |
|
TTL="10" |
|
TYPE="A" |
|
NAME="<SUBDOMAIN>" |
|
ZONE_NAME="<ROOT DOMAIN>" |
|
ZONE_ID="<ZONE_ID>" |
|
|
|
## ZoneID: https://dns.hetzner.com/ |
|
## API_TOKEN: https://dns.hetzner.com/settings/api-token |
|
|
|
parent_path="$(dirname "${BASH_SOURCE[0]}")" |
|
FILE=${parent_path}/update-hetzner-dns.log |
|
if ! [ -x "$FILE" ]; then |
|
touch "$FILE" |
|
fi |
|
|
|
LOG_FILE=${parent_path}'/update-hetzner-dns.log' |
|
|
|
### Write last run of STDOUT & STDERR as log file and prints to screen |
|
exec > >(tee $LOG_FILE) 2>&1 |
|
echo "==> $(date "+%Y-%m-%d %H:%M:%S")" |
|
|
|
# http://whatismyip.akamai.com |
|
# https://ipinfo.tw/ip |
|
|
|
IP=$(curl -s -X GET http://whatismyip.akamai.com --max-time 3) |
|
|
|
if [ -z "$IP" ]; then |
|
echo "Error! Can't get external ip from http://whatismyip.akamai.com" |
|
exit 0 |
|
fi |
|
echo "==> External IP is: $IP" |
|
|
|
## GET Zone ID |
|
ZONE_ID=$(curl "https://dns.hetzner.com/api/v1/zones" -H "Auth-API-Token: $API_TOKEN" \ |
|
| jq -r ".zones[] | select(.name == \"${ZONE_NAME}\") | .id ") |
|
|
|
## GET Domain ID |
|
RECORD_ID=$(curl "https://dns.hetzner.com/api/v1/records?zone_id=$ZONE_ID" -H "Auth-API-Token: $API_TOKEN" \ |
|
| jq -r ".records[] | select(.name == \"${NAME}\") | .id ") |
|
|
|
## Update Record |
|
hetzner_update=$(curl -X "PUT" "https://dns.hetzner.com/api/v1/records/$RECORD_ID" \ |
|
-H "Content-Type: application/json" \ |
|
-H "Auth-API-Token: $API_TOKEN" \ |
|
-d $"{ |
|
\"value\": \"$IP\", |
|
\"ttl\": $TTL, |
|
\"type\": \"$TYPE\", |
|
\"name\": \"$NAME\", |
|
\"zone_id\": \"$ZONE_ID\"}") |