Last active
August 29, 2015 14:17
-
-
Save auscompgeek/3cec62ba6d30d6d9ba45 to your computer and use it in GitHub Desktop.
update a AAAA record on CloudFlare with your computer's global IPv6 address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import os | |
import requests | |
import socket | |
CF_API_ZONE_BASE = 'https://api.cloudflare.com/client/v4/zones/' | |
# we could use something like `ip -o -6 addr show scope global`, but urgh. | |
# if I wanted a bash script, I would've written one | |
# with thanks to https://stackoverflow.com/a/20710035 | |
def get_host_ipv6(): | |
with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as sock: | |
sock.connect(('2001:db8::1234', 9)) | |
return sock.getsockname()[0] | |
with open(os.path.expanduser('~/.cloudflare.json')) as f: | |
conf = json.loads(f.read()) | |
headers = { | |
'X-Auth-Key': conf['key'], | |
'X-Auth-Email': conf['email'], | |
'Content-Type': 'application/json' | |
} | |
zones_resp = requests.get(CF_API_ZONE_BASE, params={'name': conf['zone_name']}, headers=headers).json() | |
zone = zones_resp['result'][0] | |
zone_id = zone['id'] | |
print('got zone id', zone_id) | |
cf_zone_records_endpoint = CF_API_ZONE_BASE + zone_id + '/dns_records/' | |
hostname = conf['hostname'] | |
dns_records_resp = requests.get(cf_zone_records_endpoint, params={'type': 'AAAA', 'name': hostname}, headers=headers).json() | |
records = dns_records_resp['result'] | |
print('updating hostname', hostname) | |
my_ipv6 = get_host_ipv6() | |
print('current ipv6 is', my_ipv6) | |
if records: | |
print('num records:', len(records)) | |
record = records[0] | |
print('record:', record) | |
if record['content'] != my_ipv6: | |
new_record = record.copy() | |
record_id = record['id'] | |
new_record['content'] = my_ipv6 | |
upd_rec_resp = requests.put(cf_zone_records_endpoint + record_id, data=json.dumps(new_record), headers=headers).json() | |
success = upd_rec_resp['success'] | |
else: | |
print('already up to date') | |
success = True | |
else: | |
print('no records, creating new record') | |
new_record = { | |
'type': 'AAAA', | |
'name': hostname, | |
'content': my_ipv6 | |
} | |
create_rec_resp = requests.post(cf_zone_records_endpoint, data=json.dumps(new_record), headers=headers).json() | |
success = create_rec_resp['success'] | |
print(('fail', 'success')[success]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment