This commit is contained in:
79
dyndns/cloudflare.py
Normal file
79
dyndns/cloudflare.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import requests
|
||||
import json
|
||||
import argparse
|
||||
from logging import getLogger
|
||||
from os import environ
|
||||
from .utils import get_public_ip
|
||||
|
||||
# Define your variables
|
||||
cloudflare_api_key = environ['CLOUDFLARE_API_KEY']
|
||||
|
||||
log = getLogger(__name__)
|
||||
|
||||
def update_dns_record(
|
||||
zone_id: str,
|
||||
dns_record_id: str,
|
||||
ip_address: str,
|
||||
domain_name: str,
|
||||
ttl: int,
|
||||
record_type : str,
|
||||
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": True,
|
||||
"ttl": ttl,
|
||||
"type": record_type
|
||||
}
|
||||
|
||||
# Make the PATCH request
|
||||
response = requests.patch(url, headers=headers, data=json.dumps(data))
|
||||
|
||||
# Check the response
|
||||
if response.status_code == 200:
|
||||
log.info('DNS record updated successfully:', response.json())
|
||||
else:
|
||||
msg = f'Failed to update DNS record: {response.status_code} {response.text}'
|
||||
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")
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user