Skip to content

Instantly share code, notes, and snippets.

@velp
Last active April 3, 2020 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velp/a17af3519e0491213f98b1af62b58946 to your computer and use it in GitHub Desktop.
Save velp/a17af3519e0491213f98b1af62b58946 to your computer and use it in GitHub Desktop.
Update A records for domains in DO
import sys
import os
import requests
import json
DO_API = "https://api.digitalocean.com/v2/domains/%s/records"
def get_list_of_records(token, main_domain, sub_domains):
res = requests.get(
DO_API % main_domain + "?per_page=200",
headers={
"Content-Type": "application/json",
"Authorization": "Bearer %s" % token,
}
)
res.raise_for_status()
res_records = dict()
records = res.json()["domain_records"]
print("\nFound number of records in DO: %d" % len(records))
for rec in records:
if rec["name"] not in sub_domains:
continue
res_records[rec["id"]] = {
"name": rec["name"],
"data": rec["data"],
}
return res_records
def read_app_file(path):
with open(path, "r") as f:
return json.load(f)
def update_record(token, main_domain, record_id, new_ip):
res = requests.put(
DO_API % main_domain + "/%s" % record_id,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer %s" % token,
},
json={
"data": new_ip,
}
)
res.raise_for_status()
return res.text
if __name__ == "__main__":
if len(sys.argv) < 4:
print("Usage: %s <main_domain> <new_ip_address> <json_file_with_apps>" % sys.argv[0])
sys.exit(1)
token = os.environ.get("DIGITALOCEAN_TOKEN")
if not token:
print("DigitalOcean token should be provided by env variable DIGITALOCEAN_TOKEN")
sys.exit(1)
apps = read_app_file(sys.argv[3])
print("Applications from file:")
for app in apps:
print(app)
records = get_list_of_records(token, sys.argv[1], [a['id'] for a in apps])
print("\nCurrent records:")
for id, rec in records.items():
print(id, rec)
print("\nUpdating records:")
for id, rec in records.items():
res = update_record(token, sys.argv[1], id, sys.argv[2])
print("Result for record %s: %s" % (id, res))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment