Skip to content

Instantly share code, notes, and snippets.

@ericswpark
Last active October 29, 2022 03:43
Show Gist options
  • Save ericswpark/71fdb6ffebf93f971b737644795cf37f to your computer and use it in GitHub Desktop.
Save ericswpark/71fdb6ffebf93f971b737644795cf37f to your computer and use it in GitHub Desktop.
Updates DNS entry on Cloudflare

cloudflare_ddns

Script to automatically update A DNS entry on Cloudflare

Requirements

curl and jq must be installed.

Setup

  • Grab an API key from here.
    • "Create Token"
    • "Edit zone DNS" - "Use template"
    • Give your token a descriptive name
    • "Zone Resources" - "Include" - "Specific zone" - select the target zone to modify
    • "Continue to summary"
    • "Create Token"
    • Paste the newly-created token in the token variable
  • Set the other variables accordingly
  • Run the script
  • (optional) Set up a crontab entry so it runs every once in a while.
#!/bin/bash
# Define variables here
target_domain="example.com"
target_subdomain="subdomain"
token="T-1234567891011121314151617181920"
# Fetches and saves public IP to $public_ip_address
function fetch_public_ip() {
# Get public IP (in IPv4 specification)
public_ip_address=$(curl -s http://ipv4.icanhazip.com/)
}
# Fetches and saves target zone ID to $target_zone_id
function fetch_target_zone_id() {
target_zone_id=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" | jq -r --arg domain $target_domain '.result[] | select(.name == $domain).id')
}
# Fetches and saves target DNS record ID to $target_dns_record_id
function fetch_target_dns_record_id() {
target_dns_record_id=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$target_zone_id/dns_records" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" | jq -r --arg name "$target_subdomain.$target_domain" '.result[] | select(.name == $name).id')
}
# Updates DNS entry on Cloudflare
function update_cloudflare_dns_entry() {
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$target_zone_id/dns_records/$target_dns_record_id" \
-H "Authorization: Bearer $token" \
-H "Content-Type: application/json" \
--data '{"type":"A","name":"'"$target_subdomain.$target_domain"'","content":"'"$public_ip_address"'","ttl":60,"proxied":false}'
}
function main() {
echo "Starting on $(date)..."
fetch_public_ip
echo "Your public IP is $public_ip_address."
fetch_target_zone_id
echo "The target zone ID is $target_zone_id."
fetch_target_dns_record_id
echo "The target DNS record ID is $target_dns_record_id."
update_cloudflare_dns_entry
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment