Using the Cloudflare API, this script updates the TTL (Time To Live) of DNS records. It can be useful for changing the TTL of multiple records at once.
importrequestsAPI_TOKEN=("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"# Replace with your Cloudflare API token
)ZONE_ID="00000000000000000000000000000000"# Replace with your Cloudflare Zone ID found in the dashboard
HEADERS={"Authorization":f"Bearer {API_TOKEN}","Content-Type":"application/json"}CURRENT_TTL=1TARGET_TTL=3600PROXIED=FalseTYPES=["A","AAAA","CNAME"]deflist_dns_records():page, all_records=1, []whileTrue:url=f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records?per_page=100&page={page}"response=requests.get(url,headers=HEADERS)response.raise_for_status()data=response.json()all_records.extend(data["result"])ifdata["result_info"]["total_pages"]==page:breakpage+=1returnall_recordsdefupdate_dns_record(record):url=f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/dns_records/{record['id']}"response=requests.put(url,headers=HEADERS,json=record)response.raise_for_status()returnresponse.json()dns_records=list_dns_records()print(f"Total DNS records: {len(dns_records)}")forrecordindns_records:if(record["ttl"]==CURRENT_TTLandrecord["type"]inTYPESandrecord["proxied"]isPROXIED):record["ttl"]=TARGET_TTLprint(f"Updating {record['name']} ({record['type']}) from {CURRENT_TTL} to {TARGET_TTL}")update_dns_record(record)