Skip to content

Instantly share code, notes, and snippets.

@jhthorsen
Created January 13, 2023 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhthorsen/6534b0cd61bbf2a58ca5e1647f11bdc2 to your computer and use it in GitHub Desktop.
Save jhthorsen/6534b0cd61bbf2a58ca5e1647f11bdc2 to your computer and use it in GitHub Desktop.
DDNS system for Cloudflare: Update the DNS record if the webserver does not respond correctly
[Unit]
Description=Cloudflare DDNS
After=network.target
[Service]
#Environment=CLOUDFLARE_API_KEY=
Environment=ZONE_ID=1234
Environment=RECORD_ID=5678
Environment=RECORD_NAME=domain.example.com
ExecStart=/usr/local/bin/cloudflareddns /path/to/env.sh
WorkingDirectory=/tmp
Restart=on-failure
RestartSec=5s
SyslogIdentifier=ddns
Type=simple
[Install]
WantedBy=multi-user.target
#!/bin/bash
PATH="/bin:/usr/bin";
[ -n "$1" ] && [ -e "$1" ] && source "$1";
check_environment() {
[ -z "$CLOUDFLARE_API_KEY" ] && exec echo "CLOUDFLARE_API_KEY= must be set";
[ -z "$RECORD_ID" ] && exec echo "RECORD_ID= must be set";
[ -z "$RECORD_NAME" ] && exec echo "RECORD_NAME= must be set";
[ -z "$ZONE_ID" ] && exec echo "ZONE_ID= must be set";
return 0;
}
api() {
echo "> curl $*" >&2;
curl --no-progress-meter -H "Authorization: Bearer $CLOUDFLARE_API_KEY" -H "Content-Type: application/json" "$@";
}
curlx() {
echo "> curl $*" >&2;
curl --no-progress-meter "$@";
}
ensure_environment() {
[ -z "$CHECK_INTERVAL" ] && CHECK_INTERVAL="10";
[ -z "$API_BASE" ] && API_BASE="https://api.cloudflare.com/client/v4";
[ -z "$WAN_IP_URL" ] && WAN_IP_URL="https://canhazip.com";
return 0;
}
update_record() {
local wan_ip; local data;
wan_ip="$(curlx "$WAN_IP_URL")";
[ -z "$wan_ip" ] && return 1;
data="{'type':'A','name':'$RECORD_NAME','content':'$wan_ip'}";
data="$(echo "$data" | sed 's/'\''/"/g')";
api -X PUT "$API_BASE/zones/$ZONE_ID/dns_records/$RECORD_ID" --data "$data";
echo;
}
main() {
local record_check;
while sleep "$CHECK_INTERVAL"; do
record_check="$(curlx "https://$RECORD_NAME/$RECORD_NAME.txt")";
[ "$record_check" = "$RECORD_ID" ] || update_record;
done
}
check_environment && ensure_environment && main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment