Last active
October 5, 2017 23:06
-
-
Save Kromey/5b83c7d0e0e5187f4d5183ee07bad9d9 to your computer and use it in GitHub Desktop.
Dynamic DNS via Cloudflare
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 python | |
import requests | |
import conf | |
url_base = 'https://api.cloudflare.com/client/v4{endpoint}' | |
urls = { | |
'zone_list': '/zones', | |
'record_list': '/zones/{zone_id}/dns_records', | |
'record_update': '/zones/{zone_id}/dns_records/{record_id}', | |
} | |
headers = { | |
'X-Auth-Email': conf.API_EMAIL, | |
'X-Auth-Key': conf.API_TOKEN, | |
} | |
# Get our IP address | |
my_ip = requests.get('https://api.ipify.org').text | |
# Use a Session from here on out for better performance | |
with requests.Session() as s: | |
# Set up our headers | |
s.headers.update(headers) | |
# Find our zone | |
zones = s.get(url_base.format(endpoint=urls['zone_list'])) | |
for zone in zones.json()['result']: | |
if conf.TARGET_DOMAIN.endswith(zone['name']): | |
break | |
assert conf.TARGET_DOMAIN.endswith(zone['name']) | |
# Find our domain record | |
records_url = urls['record_list'].format(zone_id=zone['id']) | |
records = s.get(url_base.format(endpoint=records_url)) | |
for record in records.json()['result']: | |
if conf.TARGET_DOMAIN == record['name']: | |
break | |
assert conf.TARGET_DOMAIN == record['name'] | |
# Update our domain record | |
update_url = urls['record_update'].format(zone_id=zone['id'], record_id=record['id']) | |
record['content'] = my_ip | |
update = s.put(url_base.format(endpoint=update_url), json=record) | |
assert update.status_code == 200 | |
assert update.json()['success'] |
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
# Copy or rename this file to conf.py | |
# Then update the values below | |
# Your Cloudflare API token | |
API_TOKEN = 'c2547eb745079dac9320b638f5e225cf483cc5cfdda41' | |
# Your Cloudflare account email address | |
API_EMAIL = 'user@example.com' | |
# The DNS record you want to update | |
TARGET_DOMAIN = 'target.example.com' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment