Skip to content

Instantly share code, notes, and snippets.

@amiller-gh
Last active April 21, 2023 15:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save amiller-gh/7d7dcb4176ee9f42f13e4fe672d4a7f5 to your computer and use it in GitHub Desktop.
Save amiller-gh/7d7dcb4176ee9f42f13e4fe672d4a7f5 to your computer and use it in GitHub Desktop.
Simple Dynamic DNS Bash Script
#!/bin/bash
# This simple bash script will auto-update a CloudFlare DNS entry if a computer's public IP address changes.
# Simply place it in a folder called /etc/ddns and add a cron job to call it every minute or so.
# The five configuration options below are specific to your account and must be set.
DOMAIN_NAME="domain.name.tld"
AUTH_EMAIL="name@email.tld"
AUTH_KEY="__cloudflare_auth_key__"
ZONE_ID="__cloudflare_zone_identifier__"
RECORD_ID="__cloudflare_record_identifier__"
# Our current IP address and path to our IP cache file
IP_ADDRESS=`dig +short myip.opendns.com @resolver1.opendns.com`
CACHE_PATH="/etc/ddns/cache.txt"
# Fetch last value of IP address sent to server or create cache file
if [ ! -f $CACHE_PATH ]; then touch $CACHE_PATH; fi
CURRENT=$(<$CACHE_PATH)
# If IP address hasn't changed, exit, otherwise save the new IP
if [ "$IP_ADDRESS" == "$CURRENT" ]; then exit 0; fi
echo $IP_ADDRESS > $CACHE_PATH
# Update CloudFlare
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" -H "X-Auth-Email: $AUTH_EMAIL" -H "X-Auth-Key: $AUTH_KEY" -H "Content-Type: application/json" --data '{"type": "A", "name": "'$DOMAIN_NAME'", "content": "'$IP_ADDRESS'"}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment