Skip to content

Instantly share code, notes, and snippets.

@atirut-w
Created January 16, 2026 11:52
Show Gist options
  • Select an option

  • Save atirut-w/db6817dedf87fd8be1fd088acfd10dc5 to your computer and use it in GitHub Desktop.

Select an option

Save atirut-w/db6817dedf87fd8be1fd088acfd10dc5 to your computer and use it in GitHub Desktop.
Cloudflare DNS Updater
#!/usr/bin/env python3
"""
This script updates Cloudflare DNS A records for specified domains to point to
the current public IP address of the machine running the script. If a domain
does not have an existing A record, it creates one.
"""
import requests
from typing import List, Optional
ZONE = ""
TOKEN = ""
DOMAINS = []
def api_request(method: str, endpoint: str, data: Optional[dict] = None) -> dict:
url = f"https://api.cloudflare.com/client/v4/{endpoint}"
headers = {"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}
response = requests.request(method, url, headers=headers, json=data)
response.raise_for_status()
json = response.json()
if not json.get("success", False):
raise Exception(f"Cloudflare API error: {json['errors']}")
return json["result"]
def get_current_ip() -> str:
response = requests.get("https://api.ipify.org?format=text")
response.raise_for_status()
return response.text.strip()
IP = get_current_ip()
print(f"Current IP address: {IP}")
for domain in DOMAINS:
print(f"Processing domain: {domain}")
records = api_request("GET", f"zones/{ZONE}/dns_records?type=A&name={domain}")
if records:
record = records[0]
if record["content"] != IP:
print(f"Updating A record for {domain} from {record['content']} to {IP}")
api_request(
"PUT",
f"zones/{ZONE}/dns_records/{record['id']}",
data={
"type": "A",
"name": domain,
"content": IP,
"ttl": 1,
"proxied": False,
},
)
else:
print(f"A record for {domain} is already up to date.")
else:
print(f"Creating new A record for {domain} with IP {IP}")
api_request(
"POST",
f"zones/{ZONE}/dns_records",
data={
"type": "A",
"name": domain,
"content": IP,
"ttl": 1,
"proxied": False,
},
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment