Skip to content

Instantly share code, notes, and snippets.

@JayWood
Last active July 6, 2024 18:53
Show Gist options
  • Save JayWood/56a8481d8ab3c0f53885dc7195945fa8 to your computer and use it in GitHub Desktop.
Save JayWood/56a8481d8ab3c0f53885dc7195945fa8 to your computer and use it in GitHub Desktop.
Update your Cloudflare A record to point to your IP with only a shell script. Useful for a cron job every 15m or so.
#!/bin/bash
# Variables (replace these with your actual values)
CF_API_TOKEN="YOUR_CLOUDFLARE_API_TOKEN"
CF_ZONE_ID="YOUR_CLOUDFLARE_ZONE_ID"
CF_RECORD_ID="YOUR_DNS_RECORD_ID"
DOMAIN="yourdomain.com"
IP_FILE="/path/to/ip_address.txt"
# Get the current public IP address
CURRENT_IP=$(curl -s https://api.ipify.org?format=json | jq -r '.ip')
# Get the last known IP address
if [ -f "$IP_FILE" ]; then
LAST_IP=$(cat $IP_FILE)
else
LAST_IP=""
fi
# Compare the IP addresses
if [ "$CURRENT_IP" != "$LAST_IP" ]; then
echo "IP has changed to $CURRENT_IP. Updating Cloudflare..."
# Update the DNS A record in Cloudflare
update_record() {
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${CF_RECORD_ID}" \
-H "Authorization: Bearer ${CF_API_TOKEN}" \
-H "Content-Type: application/json" \
--data '{"type":"A","name":"'"$DOMAIN"'","content":"'"$CURRENT_IP"'","ttl":1,"proxied":false}' | jq
}
# Run the update function
update_record
# Save the current IP address
echo $CURRENT_IP > $IP_FILE
else
echo "IP has not changed. No update needed."
fi
@JayWood
Copy link
Author

JayWood commented Jul 6, 2024

Set your cron job like so:

*/15 * * * * /path/to/Cloudflare.sh >> /path/to/cron.log 2>&1

To use this you need to install jq which is a JSON processor for linux/bash:
sudo apt-get install jq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment