-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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