#!/bin/bash #Handle Cloudflare DNS for my domains automatically #But with a shell script instead of Powershell this time timeStamp=$(date +"%Y-%m-%dT%H:%M:%S") cfToken="gbkanjmrKgCEqusC28anY3PNTrOdovurXTmbackA" myIp=$(curl "api.ipify.org" -s) cfAPIBaseURI="https://api.cloudflare.com/client/v4/" authHeader="Authorization: Bearer $cfToken" zones=$(curl -X GET "${cfAPIBaseURI}zones" --header "$authHeader" -s) #Stuff it all in a Bash array readarray -t zoneArray < <(jq -c '.result.[]' <<< $zones) # iterate through the Bash array for zone in "${zoneArray[@]}"; do zoneName=$(jq --raw-output '.name' <<< "$zone") #echo $zoneName zoneId=$(jq -r '.id' <<< "$zone") #Pull the DNS records dnsRecords=$(curl -X GET "${cfAPIBaseURI}zones/${zoneId}/dns_records" --header "$authHeader" -s) #Stuff it all in a Bash array readarray -t dnsRecordsArray < <(jq -c '.result.[]' <<< $dnsRecords) # iterate through the Bash array for dnsRecord in "${dnsRecordsArray[@]}"; do dnsRecordType=$(jq -r '.type' <<< "$dnsRecord") #A records only, pls if [ $dnsRecordType == "A" ] then #Check the IP dnsRecordIp=$(jq -r '.content' <<< "$dnsRecord") #Never mind the TailScale ones and the ones matching myIp (The latter 'cause they don't need to be changed) [[ "$dnsRecordIp" =~ ^100|$myIp ]] && continue || #echo "Found a mismatch in the A record for zone ID ${zoneId}" #Get the record ID dnsRecordId=$(jq -r '.id' <<< "$dnsRecord") comment="${timeStamp} | Updated automatically from ${dnsRecordIp} to ${myIp}" content="${myIp}" #Build a JSON array to send to Cloudflare as the request body recordBody=$(jq -n -c \ --arg comment "${comment}" \ --arg content "${content}" \ '{comment: $comment, content: $content}') #Now send that body to Cloudflare so the changes are made result=$(curl -X PATCH "${cfAPIBaseURI}zones/${zoneId}/dns_records/${dnsRecordId}" --header "$authHeader" --header "Content-Type: application/json" -d "${recordBody}" -s) #Parse the JSON result success=$(jq -r '.success' <<< "$result") #echo $success if [ $success ] then echo "Successfully updated the A record for ${zoneName} from ${dnsRecordIp} to ${myIp}" else echo "Failed to update the A record for ${zoneName} from ${dnsRecordIp} to ${myIp}" fi fi done done