Files
wdyndns/dyndns/cloudflare.py
Walter Oggioni 3ae5a865fe
All checks were successful
CI / build (push) Successful in 45s
added Cloudflare API support
2025-03-31 19:08:28 +08:00

81 lines
2.6 KiB
Python

import json
import argparse
from os import environ
from .utils import get_public_ip
from urllib.request import urlopen, Request
# Define your variables
cloudflare_api_key = environ['CLOUDFLARE_API_KEY']
def update_dns_record(
zone_id: str,
dns_record_id: str,
ip_address: str,
domain_name: str,
ttl: int,
record_type : str,
proxied : bool = False,
comment : str = None
):
# Set the URL
url = f'https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{dns_record_id}'
# Set the headers
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {cloudflare_api_key}'
}
# Define the data to be sent in the PATCH request
data = {
"comment": comment,
"content": ip_address,
"name": domain_name,
"proxied": proxied,
"ttl": ttl,
"type": record_type
}
# Make the PATCH request
request = Request(url, headers=headers, data=json.dumps(data).encode('UTF-8'), method='PATCH')
with urlopen(request) as request:
if request.status != 200:
response = request.read().decode()
msg = f'Failed to update DNS record: {request.status} {response}'
raise RuntimeError(msg)
def run():
parser = argparse.ArgumentParser()
parser.add_argument('-z', "--hosted-zone", metavar='HOSTED_ZONE_ID', required=True,
help="Specify the hosted zone id")
parser.add_argument('-d', "--domain", metavar='DOMAIN_NAME', required=True,
help="Specify domain name")
parser.add_argument('-t', "--type", metavar='DNS_TYPE', default='A',
help="Specify DNS type")
parser.add_argument('-l', "--ttl", metavar='TTL_S', type=int, default=300,
help="Specify time-to-live in seconds")
parser.add_argument('-r', "--record-id", metavar='RECORD_ID',
help="Cloudflare DNS record id")
parser.add_argument('-p', "--proxied", metavar='PROXIED', type=bool, default=False,
help="Whether or not the traffic will be proxied through Cloudflare network")
parser.add_argument('-c', "--comment", metavar='COMMENT', help="Specify a comment for this entry")
args = parser.parse_args()
public_ip = get_public_ip()
update_dns_record(
zone_id=args.hosted_zone,
domain_name=args.domain,
record_type=args.type,
ip_address=public_ip,
ttl=args.ttl,
dns_record_id=args.record_id,
proxied=args.proxied,
comment=args.comment
)