Skip to content

Instantly share code, notes, and snippets.

@psa-jforestier
Last active January 23, 2026 19:36
Show Gist options
  • Select an option

  • Save psa-jforestier/27c958a6cfc6669d8576b8e67013e6d9 to your computer and use it in GitHub Desktop.

Select an option

Save psa-jforestier/27c958a6cfc6669d8576b8e67013e6d9 to your computer and use it in GitHub Desktop.
A Bash script to update a DNS record using Cloudflare DNS API and your public ip get from ipify.org
#!/bin/bash
#
# get an api key :
# Cloudflare console : Manage account > Account API tokens
# Create tokens
# Select Edit Zone DNS use Template
# Configure access right (edit zone dns for the domain)
# Retreive the CLOUDFLARE_API_TOKEN from here
#
# For the ZONE_ID :
# When logged on Cloudflare, go to the DNS page of your domain,
# scroll down and look for the "Zone ID" area.
ZONE_ID=12345678abcdef
CLOUDFLARE_API_TOKEN=abcdeghijkln
date
echo "Requesting current public ip by using https://api.ipify.org/"
# Get public IP from ipify.org
newip=$(curl -s "https://api.ipify.org/")
if [[ "$newip" == "" ]]; then
echo "!! ipfy failed !!"
exit
fi
echo "Public ip is $newip"
newhostname=$(host $newip | cut -d ' ' -f 5);
echo "Hostname is $newhostname";
# Check current DNS record
DNS_RECORD=$(curl -s https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" | jq -r '.result[] | select(.name == "box.forestier.xyz") ')
if [[ "$DNS_RECORD" == "" ]]; then
echo "!! cloudflare API failed to get DNS record !!"
exit
fi
DNS_RECORD_ID=$(echo $DNS_RECORD | jq -r '.id')
DNS_RECORD_CONTENT=$(echo $DNS_RECORD | jq -r '.content')
echo "New IP : $newip ; old record : $DNS_RECORD_CONTENT"
if [[ "$DNS_RECORD_CONTENT" != "$newip" ]]; then
echo "Updating this record with $newip"
NEW_DNS_RECORD=$(echo "$DNS_RECORD" | sed "s/\"content\": \"[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\"/\"content\": \"$newip\"/")
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$DNS_RECORD_ID" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
-H "Content-Type: application/json" \
--data "$NEW_DNS_RECORD"
echo "Done"
else
echo "No change on IP, nothing to update"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment