2023-12-23 01:22:41 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
import argparse
|
|
|
|
import subprocess
|
|
|
|
|
2025-03-08 18:47:04 +00:00
|
|
|
import cloudflare
|
2023-12-23 01:22:41 +00:00
|
|
|
|
|
|
|
def main():
|
|
|
|
parser = argparse.ArgumentParser(description='Cloudflare DNS update script')
|
|
|
|
parser.add_argument('-k', '--api-token-file', help='Cloudflare API token file')
|
|
|
|
parser.add_argument('zone', help='Cloudflare Zone')
|
|
|
|
parser.add_argument('record', help='Cloudflare record name')
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
|
|
|
address = subprocess.check_output(
|
|
|
|
['drill', '-Q', '-p5353', '@127.0.0.1', args.record, 'A'],
|
|
|
|
encoding='utf8').strip()
|
|
|
|
|
|
|
|
cf_token = None
|
|
|
|
if args.api_token_file:
|
|
|
|
with open(args.api_token_file) as f:
|
|
|
|
cf_token = f.readline().strip()
|
2025-03-08 18:47:04 +00:00
|
|
|
cf = cloudflare.Cloudflare(api_token=cf_token)
|
2023-12-23 01:22:41 +00:00
|
|
|
|
2025-03-08 18:47:04 +00:00
|
|
|
zones = list(cf.zones.list(name=args.zone))
|
2023-12-23 01:22:41 +00:00
|
|
|
assert zones, f'Zone {args.zone} not found'
|
2025-03-08 18:47:04 +00:00
|
|
|
assert len(zones) == 1, f'More than one zone found for {args.zone}'
|
|
|
|
zone = zones[0]
|
|
|
|
|
|
|
|
records = list(cf.dns.records.list(zone_id=zone.id, name=args.record, type='A'))
|
2023-12-23 01:22:41 +00:00
|
|
|
assert records, f'Record {args.record} not found in zone {args.zone}'
|
2025-03-08 18:47:04 +00:00
|
|
|
assert len(records) == 1, f'More than one record found for {args.record}'
|
|
|
|
record = records[0]
|
2023-12-23 01:22:41 +00:00
|
|
|
|
|
|
|
print(f'Updating {args.record} -> {address}')
|
2025-03-08 18:47:04 +00:00
|
|
|
cf.dns.records.edit(
|
|
|
|
zone_id=zone.id, dns_record_id=record.id,
|
|
|
|
type='A', content=address)
|
2023-12-23 01:22:41 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|