Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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