-
-
Save dextervip/1b90a447288a428a64f91b7dd6dbbf77 to your computer and use it in GitHub Desktop.
Python Cloudflare Dynamic DNS Update script
This file contains hidden or 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 | |
""" | |
Update Cloudflare zone entry to current external IP. | |
Works great with servers on changing IPs or AWS spot instances. | |
Usage: | |
python cloudflare_update.py subdomain | |
""" | |
import sys | |
import json | |
import requests | |
import os | |
EMAIL = os.environ['CLOUDFLARE_EMAIL'] | |
KEY = os.environ['CLOUDFLARE_KEY'] | |
ZONE = os.environ['CLOUDFLARE_ZONE'] | |
RECORD = sys.argv[1] | |
CONTENT = requests.get('http://jsonip.com').json()['ip'] | |
headers = {'X-Auth-Key': KEY, 'X-Auth-Email': EMAIL, 'Content-type': 'application/json'} | |
base_url = 'https://api.cloudflare.com/client/v4{}' | |
# Get Zone ID | |
r = requests.get(base_url.format('/zones'), headers=headers) | |
for res in r.json()['result']: | |
if res['name'] == ZONE: | |
ZONE_ID = res['id'] | |
# Get list of Zone DNS records | |
RECORD_ID = None | |
url_path = '/zones/{}/dns_records'.format(ZONE_ID) | |
r = requests.get(base_url.format(url_path), headers=headers) | |
for res in r.json()['result']: | |
if res['name'] == '{}.{}'.format(RECORD, ZONE): | |
RECORD_ID = res['id'] | |
# Update or add Zone Record. | |
JSON_CONTENT = json.dumps({'type': 'A', 'name': RECORD, 'content': CONTENT, 'proxied': False }) | |
if RECORD_ID: | |
print(f'Updating record {RECORD_ID}...') | |
url_path = '/zones/{}/dns_records/{}'.format(ZONE_ID, RECORD_ID) | |
url = base_url.format(url_path) | |
print(requests.put(url, headers=headers, data=JSON_CONTENT)) | |
else: | |
print('Creating record...') | |
url_path = '/zones/{}/dns_records'.format(ZONE_ID) | |
url = base_url.format(url_path) | |
print(requests.post(url, headers=headers, data=JSON_CONTENT)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment