From 74a6b83d752ca5fd2828efc25c01912beadb72b2 Mon Sep 17 00:00:00 2001 From: Vasily Davydov Date: Tue, 4 Jun 2024 13:31:48 +0300 Subject: [PATCH] services: add script to update cloudflare dns records --- services/.gitignore | 1 + services/cloudflare_update_dns | 51 ++++++++++++++++++++++++++++++++++ services/send_telegram | 4 +-- 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 services/.gitignore create mode 100755 services/cloudflare_update_dns diff --git a/services/.gitignore b/services/.gitignore new file mode 100644 index 0000000..75408e9 --- /dev/null +++ b/services/.gitignore @@ -0,0 +1 @@ +**/.var diff --git a/services/cloudflare_update_dns b/services/cloudflare_update_dns new file mode 100755 index 0000000..cf1fa6d --- /dev/null +++ b/services/cloudflare_update_dns @@ -0,0 +1,51 @@ +#! /usr/bin/env bash + +set -euo pipefail + +mkdir -p .var + +ZONE_ID="$(cat .var/zone_id)" +DNS_RECORD="$(cat .var/dns_record)" +CACHED_PUBLIC_IP="$(cat .var/cached_public_ip)" +AUTHORIZATION="$(cat .var/bearer)" + +IP_URL="ifconfig.me/ip" +SEND_TELEGRAM="$(pwd)/send_telegram" + +function info() { + echo "$(date --iso-8601=minutes) CLOUDFLARE_DNS_UPDATE [INFO]: ${*}" +} +function error() { + echo "$(date --iso-8601=minutes) CLOUDFLARE_DNS_UPDATE [ERROR]: ${*}" +} + + +function check_new_ip() { + local new_ip + new_ip="$(curl -s ${IP_URL})" + if [[ "${new_ip}" == "${CACHED_PUBLIC_IP}" ]]; then + info "Public IP has not changed from ${new_ip}. Exiting..." + exit 0; + else + info "Public IP has changed from ${CACHED_PUBLIC_IP} to ${new_ip}. Updating records..." + "${SEND_TELEGRAM}" "Public IP has changed from ${CACHED_PUBLIC_IP} to ${new_ip}. Updating records..." + CACHED_PUBLIC_IP="${new_ip}" + echo "${new_ip}" > .var/cached_public_ip + fi +} + +check_new_ip + +curl --request PATCH \ + --url "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/dns_records/${DNS_RECORD}" \ + --header 'Content-Type: application/json' \ + --header 'X-Auth-Email: ' \ + --data '{ + "content": "'${CACHED_PUBLIC_IP}'", + "name": "tylencloud.com", + "proxied": false, + "type": "A", + "comment": "Main Record", + "ttl": 3600 +}' \ +-H "Authorization: Bearer ${AUTHORIZATION}"; diff --git a/services/send_telegram b/services/send_telegram index 11ba446..f5e106b 100755 --- a/services/send_telegram +++ b/services/send_telegram @@ -7,8 +7,8 @@ if [ "$#" -ne 1 ]; then fi # Set the API token and chat ID -API_TOKEN="7074090911:AAEoazbp1LcqRE7qq9Jf71sXpQaQOz-D0fc" -CHAT_ID="1622364607" +API_TOKEN="$(cat .var/telegram_bot_api_token)" +CHAT_ID="$(cat .var/telegram_bot_chat_id)" MESSAGE="$1"