-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.py
77 lines (57 loc) · 2.3 KB
/
update.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
import requests
import ConfigParser
import os
def get_ip():
response = requests.get('https://icanhazip.com')
if response.status_code != requests.codes.ok:
return None
else:
return response.text.rstrip('\n')
def update_rackspace(config, ip):
import pyrax
def clear_records(domain, fqdn):
for record in [item for item in dns.get_record_iterator(domain)
if item.name == fqdn]:
dns.delete_record(domain, record)
domain_list = dict(config.items('domain_records'))
api_user = config.get('rackspace', 'username')
api_key = config.get('rackspace', 'apikey')
pyrax.settings.set('identity_type', 'rackspace')
pyrax.set_credentials(api_user, api_key)
dns = pyrax.cloud_dns
dns.set_timeout(timeout=60)
for domain in [item for item in dns.get_domain_iterator()
if item.name in domain_list]:
fqdn = '{0}.{1}'.format(domain_list[domain.name], domain.name)
update_record = {
'records': [
{
'type': 'A',
'name': fqdn,
'data': ip,
'ttl': 300
}
]
}
try:
record = dns.find_record(domain, record_type='A', name=fqdn)
update_record['records'][0]['id'] = record.id
dns.update_records(domain, update_record)
except (pyrax.exc.DomainRecordNotFound, pyrax.exc.DomainRecordNotUnique):
# even if we don't find the record originally, we want to delete any potential conflicts
clear_records(domain, fqdn)
dns.add_records(domain, update_record['records'])
def main():
config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/.config/updateip.conf'))
if not config.has_section('config'):
raise Exception('[config] section missing from configuration file')
provider = config.get('config', 'provider')
if not config.has_section(provider):
raise Exception('[{0}] section missing from configuration file'.format(provider))
if not config.has_section('domain_records'):
raise Exception('[domain_records] section missing from configuration file')
ip = get_ip()
update_rackspace(config, ip)
if __name__ == '__main__':
main()