Skip to content

Instantly share code, notes, and snippets.

@ropable
Forked from Tras2/cloudflare-ddns-update.sh
Last active May 28, 2021 13:49
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 ropable/c5ba41f0aacf45bff614be312f854694 to your computer and use it in GitHub Desktop.
Save ropable/c5ba41f0aacf45bff614be312f854694 to your computer and use it in GitHub Desktop.
A bash script to update a Cloudflare DNS A record with the external IP of the source machine
#!/bin/bash
ZONE=domain.com
DNSRECORD=sub.domain.com
TOKEN=<token>
# Get the current external IP address
IP=$(curl -s -X GET https://checkip.amazonaws.com)
CURRENTDATE=`date`
echo $CURRENTDATE
echo "Current IP is $IP"
if host $DNSRECORD 1.1.1.1 | grep "has address" | grep "$IP"; then
echo "No update required"
exit
fi
# If here, the DNS A record needs updating
# Get the zone id for the requested zone
ZONEID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$ZONE&status=active" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id')
echo "Zoneid for $ZONE is $ZONEID"
# Get the DNS record id
DNSRECORDID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONEID/dns_records?type=A&name=$DNSRECORD" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" | jq -r '{"result"}[] | .[0] | .id')
echo "DNS record ID for $DNSRECORD is $DNSRECORDID"
# Update the record
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONEID/dns_records/$DNSRECORDID" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$DNSRECORD\",\"content\":\"$IP\",\"ttl\":1,\"proxied\":false}" | jq
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment