Skip to content

Instantly share code, notes, and snippets.

@Dilden
Last active February 12, 2021 02:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dilden/cbe4787b5e776eb13989df1ba8b54612 to your computer and use it in GitHub Desktop.
Save Dilden/cbe4787b5e776eb13989df1ba8b54612 to your computer and use it in GitHub Desktop.
DDNS via Cloudflare API
#/usr/bin/env sh
# Date
DATE=`date +%Y-%m-%d_%H:%M:%S`
# Get the ZoneID from: https://www.cloudflare.com/a/overview/<your-domain>
DNS_ZONE=YOUR_ZONE_ID_HERE
# Get the existing identifier for DNS entry:
# https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
IDENTIFIER=YOUR_DNS_ENTRY
# Get these from: https://www.cloudflare.com/a/account/my-account
AUTH_EMAIL=YOUR_EMAIL
AUTH_KEY=YOUR_GLOBAL_AUTH_KEY
# Desired domain name
DOMAIN_NAME="YOU_DOMAIN_NAME_HERE"
# Get previous IP address
_PREV_IP_FILE="/tmp/public-ip.txt"
_PREV_IP=$(cat $_PREV_IP_FILE)
# Install `dig` via `dnsutils` for faster IP lookup.
eval dig &> /dev/null && {
_IP=$(dig +short myip.opendns.com @resolver1.opendns.com)
} || {
_IP=$(curl --silent https://api.ipify.org)
} || {
exit 1
}
# If new/previous IPs match, no need for an update.
if [ "$_IP" = "$_PREV_IP" ]; then
exit 0
fi
_UPDATE=$(cat <<EOF
{ "type": "A",
"name": "$DOMAIN_NAME",
"content": "$_IP",
"ttl": 120,
"proxied": true }
EOF
)
curl "https://api.cloudflare.com/client/v4/zones/$DNS_ZONE/dns_records/$IDENTIFIER" \
--silent \
-X PUT \
-H "Content-Type: application/json" \
-H "X-Auth-Email: $AUTH_EMAIL" \
-H "X-Auth-Key: $AUTH_KEY" \
-d "$_UPDATE" > /tmp/cloudflare-ddns-update.json && \
echo $_IP > $_PREV_IP_FILE
echo "IP updated to: $_IP on $DATE";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment