-
Notifications
You must be signed in to change notification settings - Fork 2
/
upload_zone_file.py
executable file
·80 lines (62 loc) · 2.36 KB
/
upload_zone_file.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
#!/usr/bin/env python
import json
import logging
import os
import sys
import requests
from blockstack_zones import parse_zone_file
FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
log = logging.getLogger(__name__)
API_TOKEN = os.environ['DO_API_TOKEN']
def create_domain_record(domain, **kwargs):
headers = {
'Authorization': 'Bearer ' + API_TOKEN,
'Content-Type': 'application/json',
}
endpoint = 'https://api.digitalocean.com/v2/domains/{}/records'.format(domain)
response = requests.post(endpoint, data=json.dumps(kwargs), headers=headers)
if response.ok:
log.info('Created new %s record %s.', kwargs['type'], kwargs['name'])
else:
error_message = response.json()['message']
log.error('Failed to create %s record %s. Error was: %s', kwargs['type'], kwargs['name'], error_message)
def main(argv):
domain_name, zone_file = _parse_zone_file(argv[0])
for record_type, records in zone_file.items():
record_type = record_type.upper()
# NOTE: I default to the Gmail option in the UI.
# NS and SOA records should be provided by DigitalOcean.
if record_type not in ('MX', 'NS', 'SOA'):
for record in records:
if record_type == 'CNAME':
record['data'] = record['alias'] + '.'
elif record_type == 'TXT':
record['data'] = record['txt']
elif record_type == 'A':
record['data'] = record['ip']
create_domain_record(
domain_name,
type=record_type,
name=record['name'],
ttl=record['ttl'],
data=record['data']
)
def _parse_zone_file(path):
"""
Parse the zone file.
Args:
path (str): Path to the zone file
Returns:
str: Domain name
dict[]: Domain records
"""
log.info('Parsing %s...', path)
with open(path, 'r') as f:
zone_file = parse_zone_file(f.read())
domain_name = zone_file.pop('$origin').strip('.')
record_count = sum([len(records) for records in zone_file.itervalues()])
log.info('Parsed %d records for %s.', record_count, domain_name)
return domain_name, zone_file
if __name__ == '__main__':
main(sys.argv[1:])