Skip to content

Instantly share code, notes, and snippets.

@lukedesu
Last active July 11, 2023 18:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukedesu/80751505133828c122470bc56388b6c0 to your computer and use it in GitHub Desktop.
Save lukedesu/80751505133828c122470bc56388b6c0 to your computer and use it in GitHub Desktop.
Bash script to update Cloudflare DNS record. step 1: sudo chmod +x cloudflare.sh step2: */10 * * * * /bin/bash ~/cloudflare.sh
#!/bin/bash
auth_email="someone@gmail.com" # The email used to login 'https://dash.cloudflare.com'
auth_key="your Global API Key" # Top right corner, "My profile" > "Global API Key"
zone_identifier="your domain's Zone ID" # Can be found in the "Overview" tab of your domain
record_name="test.example.com" # Which record you want to be synced
proxy=false # Set the proxy to true or false
###########################################
## Check if we have a public IP
###########################################
ip=$(curl -s https://ipv4.icanhazip.com/ || curl -s https://api.ipify.org)
if [ "${ip}" == "" ]; then
message="No public IP found."
>&2 echo -e "${message}" >> ~/log
exit 1
fi
###########################################
## Seek for the A record
###########################################
echo " Check Initiated" >> ~/log
record=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records?name=$record_name" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json")
###########################################
## Set the record identifier from result
###########################################
record_identifier=$(echo "$record" | grep -Po '(?<="id":")[^"]*' | head -1)
###########################################
## Change the IP@Cloudflare using the API
###########################################
update=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records/$record_identifier" -H "X-Auth-Email: $auth_email" -H "X-Auth-Key: $auth_key" -H "Content-Type: application/json" --data "{\"type\":\"A\",\"proxied\":${proxy},\"name\":\"$record_name\",\"content\":\"$ip\"}")
###########################################
## Report the status
###########################################
case "$update" in
*""success":false"*)
message="$ip $record_name DDNS failed for $record_identifier ($ip). DUMPING RESULTS:n$update"
>&2 echo -e "${message}" >> ~/log
exit 1;;
*)
message="$ip $record_name DDNS updated."
echo "${message}" >> ~/log
exit 0;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment