forked from solrex/certbot-vultr-dns-auth-hook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vultr-dns.py
executable file
·85 lines (61 loc) · 2.44 KB
/
vultr-dns.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python
import requests
import sys
import os
import string
from time import sleep
# Configure here
VULTR_API_KEY = "put your api key here"
VULTR_BIND_DELAY = 30
def vultr_request(method, zone, path, data=None):
url = f"https://api.vultr.com/v2/domains{zone}{path}"
resp = requests.request(method, url, json=data, headers={
"Authorization": "Bearer " + VULTR_API_KEY})
resp.raise_for_status()
if resp.headers["Content-Type"] == "application/json":
return resp.json()
return resp.text
def find_zone_for_name(domain):
resp = vultr_request("GET", "", "")
zones = [entry["domain"] for entry in resp["domains"]]
# api doesn't have a trailing . on its zones
if domain[-1:] == ".":
domain = domain[:-1]
domain_split = domain.split(".")
while len(domain_split) > 0:
search = ".".join(domain_split)
if search in zones:
return search
domain_split = domain_split[1:]
raise Exception(f"Could not identify existing zone for {domain}")
def list_records(zone):
return vultr_request("GET", "/" + zone, "/records")
def create_record(domain, txt_value):
to_add = f"_acme-challenge.{domain}".lower()
print(f"Creating {to_add} TXT: {txt_value}")
zone = find_zone_for_name(domain)
create_params = {"name": to_add, "type": "TXT", "data": f"{txt_value}"}
vultr_request("POST", "/" + zone, "/records", create_params)
print(f"Will sleep {VULTR_BIND_DELAY} seconds to wait for DNS cluster to reload")
sleep(VULTR_BIND_DELAY)
def remove_record(domain, txt_value):
to_remove = f"_acme-challenge.{domain}".lower()
zone = find_zone_for_name(to_remove)
recs = list_records(zone)
print(f"Removing {to_remove} TXT: {txt_value}")
to_remove = to_remove[:-len(zone)-1]
found = [rec for rec in recs["records"] if rec.get("name") == to_remove and rec.get("type") == "TXT" and rec["data"] == f"\"{txt_value}\""]
if len(found) == 0:
print(f"Could not find record to remove: {to_remove} with value {txt_value}")
return
vultr_request("DELETE", "/" + zone, "/records/" + found[0]["id"])
act = sys.argv[1]
if act == "create":
create_record(os.environ["CERTBOT_DOMAIN"],
os.environ["CERTBOT_VALIDATION"])
elif act == "delete":
remove_record(os.environ["CERTBOT_DOMAIN"],
os.environ["CERTBOT_VALIDATION"])
else:
print(f"Unknown action: {act}")
exit(1)