Created
May 10, 2019 03:49
-
-
Save mattrasband/b9d8b467490cbaa06f5a4295bf1c19dc to your computer and use it in GitHub Desktop.
Quick script to dynamically configure my digital ocean dns for home IP rotation
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 | |
from pathlib import Path | |
from urllib.request import Request, urlopen | |
DOMAIN = os.environ["DOMAIN"] # hostname, like google.com | |
SUBDOMAIN = os.environ["SUB_DOMAIN"] # subdomain, like mail<.google.com> | |
DO_TOKEN = os.environ["DIGITALOCEAN_TOKEN"] # token for digital ocean | |
def current_ip() -> str: | |
with urlopen("https://checkip.amazonaws.com") as r: | |
return r.read().strip().decode() | |
def current_dns_ip(domain: str, subdomain: str, do_token: str) -> str: | |
req = Request( | |
f"https://api.digitalocean.com/v2/domains/{domain}/records", | |
headers={ | |
"Authorization": f"Bearer {do_token}", | |
}, | |
) | |
with urlopen(req) as r: | |
records = json.load(r) | |
for record in records["domain_records"]: | |
if record["name"] == subdomain: | |
return record | |
return {} | |
def create_a_record(ip: str, domain: str, subdomain: str, do_token: str) -> dict: | |
req = Request( | |
f"https://api.digitalocean.com/v2/domains/{domain}/records", | |
headers={ | |
"Authorization": f"Bearer {do_token}", | |
"Content-Type": "application/json", | |
}, | |
data=json.dumps({ | |
"type": "A", | |
"name": subdomain, | |
"data": ip, | |
"priority": None, | |
"port": None, | |
"ttl": 1800, | |
"weight": None, | |
}).encode(), | |
method="POST", | |
) | |
with urlopen(req) as r: | |
return json.load(r)["domain_record"] | |
def update_record(record: dict, domain: str, do_token: str) -> dict: | |
req = Request( | |
f"https://api.digitalocean.com/v2/domains/{domain}/records/{record['id']}", | |
headers={ | |
"Authorization": f"Bearer {do_token}", | |
"Content-Type": "application/json", | |
}, | |
data=json.dumps(record).encode(), | |
method="PUT", | |
) | |
with urlopen(req) as r: | |
return json.load(r)["domain_record"] | |
def main(): | |
home_ip = current_ip() | |
print("Home IP:", home_ip) | |
dns_record = current_dns_ip(DOMAIN, SUBDOMAIN, DO_TOKEN) | |
if dns_record and dns_record["data"] == home_ip: | |
print("Existing record OK") | |
elif dns_record: | |
print(f"Updating existing record (old: {dns_record['data']}, new: {home_ip})") | |
dns_record["data"] = home_ip | |
record = update_record(dns_record, DOMAIN, DO_TOKEN) | |
print(record) | |
else: | |
print("No existing record, creating...") | |
record = create_a_record(home_ip, DOMAIN, SUBDOMAIN, DO_TOKEN) | |
print(record) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment