Skip to content

Instantly share code, notes, and snippets.

@zubir2k
Created November 5, 2023 09:26
Show Gist options
  • Save zubir2k/42e250e1831c6637a6aae6f4bdca5e15 to your computer and use it in GitHub Desktop.
Save zubir2k/42e250e1831c6637a6aae6f4bdca5e15 to your computer and use it in GitHub Desktop.
Cloudflare

Cloudflare DNS Bash Script

Simple bash script that will update your A record to your current IP.
This script can be used in Synology Task Scheduler.

image

Preparing Setup

  1. To get your Cloudflare Zone ID and API key, log in to the Cloudflare Dashboard for the domain you want to use. Your Zone ID will be displayed in the bottom right corner.

  2. To get your API Key, create an API Token with Zone:Zone:Read and Zone:DNS:Edit permissions for all zones in your account. Cloudflare API Tokens Guide

  3. To get your Record ID, run this command line after getting both Zone ID and API key:

curl -s -X GET "https://api.cloudflare.com/client/v4/zones/YOUR_ZONE_ID/dns_records?name=example.com" -H "Authorization:Bearer YOUR_API_KEY" -H "Content-Type: application/json"

Cloudflare will return a string that begins with {"result":[{"id":"abcdefg12345", - the string in quotes after “id’: is your record ID.

  1. Store the 3 items into the bash script.

Setting up in Synology

  1. Go to Synology Control Panel > Task Scheduler
  2. Create new > Scheduled Task > User-defined Script
  3. Provide a name to your task as Cloudflare, select user as root
  4. At the Schedule tab, set as Daily, and set Time to run every 10min (or to your preference).
    (Dont forget to select end time at 23:50)

image

  1. Go to Task settings tab, and paste the bash script at the Run Command.
  2. Press OK to save. Enter your Synology password to continue.
  3. You may run the script for the first time.
#!/bin/bash
# Your Cloudflare API credentials
api_key="YOUR_API_KEY"
zone_id="YOUR_ZONE_ID"
record_id="YOUR_RECORD_ID"
# Domain
domain="example.com" # Replace with your domain
# Get your current IP address from a web service
new_ip=$(curl -s https://ipinfo.io/ip)
# Cloudflare API endpoint URL
url="https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$record_id"
# Set the headers for the request
headers="Authorization: Bearer $api_key"
content_type="Content-Type: application/json"
# Create JSON data for the A record update
data="{\"type\":\"A\",\"name\":\"$domain\",\"content\":\"$new_ip\",\"ttl\":1,\"proxied\":true}"
# Make a PUT request to update the A record
response=$(curl -s -X PUT -H "$headers" -H "$content_type" --data "$data" "$url")
# Check if the response indicates success
if [[ $response == *"\"success\":true"* ]]; then
echo "A record updated successfully."
echo "IP: $new_ip"
else
echo "Failed to update A record."
echo "Response: $response"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment