mirror of
https://github.com/ansible-collections/community.general.git
synced 2026-03-26 21:33:12 +00:00
Reformat everything.
This commit is contained in:
@@ -368,7 +368,6 @@ from ansible.module_utils.urls import fetch_url
|
||||
|
||||
|
||||
class DME2:
|
||||
|
||||
def __init__(self, apikey, secret, domain, sandbox, module):
|
||||
self.module = module
|
||||
|
||||
@@ -376,37 +375,39 @@ class DME2:
|
||||
self.secret = secret
|
||||
|
||||
if sandbox:
|
||||
self.baseurl = 'https://api.sandbox.dnsmadeeasy.com/V2.0/'
|
||||
self.baseurl = "https://api.sandbox.dnsmadeeasy.com/V2.0/"
|
||||
self.module.warn(warning=f"Sandbox is enabled. All actions are made against the URL {self.baseurl}")
|
||||
else:
|
||||
self.baseurl = 'https://api.dnsmadeeasy.com/V2.0/'
|
||||
self.baseurl = "https://api.dnsmadeeasy.com/V2.0/"
|
||||
|
||||
self.domain = str(domain)
|
||||
self.domain_map = None # ["domain_name"] => ID
|
||||
self.record_map = None # ["record_name"] => ID
|
||||
self.records = None # ["record_ID"] => <record>
|
||||
self.domain_map = None # ["domain_name"] => ID
|
||||
self.record_map = None # ["record_name"] => ID
|
||||
self.records = None # ["record_ID"] => <record>
|
||||
self.all_records = None
|
||||
self.contactList_map = None # ["contactList_name"] => ID
|
||||
|
||||
# Lookup the domain ID if passed as a domain name vs. ID
|
||||
if not self.domain.isdigit():
|
||||
self.domain = self.getDomainByName(self.domain)['id']
|
||||
self.domain = self.getDomainByName(self.domain)["id"]
|
||||
|
||||
self.record_url = f"dns/managed/{self.domain}/records"
|
||||
self.monitor_url = 'monitor'
|
||||
self.contactList_url = 'contactList'
|
||||
self.monitor_url = "monitor"
|
||||
self.contactList_url = "contactList"
|
||||
|
||||
def _headers(self):
|
||||
currTime = self._get_date()
|
||||
hashstring = self._create_hash(currTime)
|
||||
headers = {'x-dnsme-apiKey': self.api,
|
||||
'x-dnsme-hmac': hashstring,
|
||||
'x-dnsme-requestDate': currTime,
|
||||
'content-type': 'application/json'}
|
||||
headers = {
|
||||
"x-dnsme-apiKey": self.api,
|
||||
"x-dnsme-hmac": hashstring,
|
||||
"x-dnsme-requestDate": currTime,
|
||||
"content-type": "application/json",
|
||||
}
|
||||
return headers
|
||||
|
||||
def _get_date(self):
|
||||
locale.setlocale(locale.LC_TIME, 'C')
|
||||
locale.setlocale(locale.LC_TIME, "C")
|
||||
return strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())
|
||||
|
||||
def _create_hash(self, rightnow):
|
||||
@@ -418,7 +419,7 @@ class DME2:
|
||||
data = urlencode(data)
|
||||
|
||||
response, info = fetch_url(self.module, url, data=data, method=method, headers=self._headers())
|
||||
if info['status'] not in (200, 201, 204):
|
||||
if info["status"] not in (200, 201, 204):
|
||||
self.module.fail_json(msg=f"{url} returned {info['status']}, with body: {info['msg']}")
|
||||
|
||||
try:
|
||||
@@ -428,22 +429,22 @@ class DME2:
|
||||
|
||||
def getDomain(self, domain_id):
|
||||
if not self.domain_map:
|
||||
self._instMap('domain')
|
||||
self._instMap("domain")
|
||||
|
||||
return self.domains.get(domain_id, False)
|
||||
|
||||
def getDomainByName(self, domain_name):
|
||||
if not self.domain_map:
|
||||
self._instMap('domain')
|
||||
self._instMap("domain")
|
||||
|
||||
return self.getDomain(self.domain_map.get(domain_name, 0))
|
||||
|
||||
def getDomains(self):
|
||||
return self.query('dns/managed', 'GET')['data']
|
||||
return self.query("dns/managed", "GET")["data"]
|
||||
|
||||
def getRecord(self, record_id):
|
||||
if not self.record_map:
|
||||
self._instMap('record')
|
||||
self._instMap("record")
|
||||
|
||||
return self.records.get(record_id, False)
|
||||
|
||||
@@ -459,7 +460,7 @@ class DME2:
|
||||
|
||||
if record_type in ["CNAME", "ANAME", "HTTPRED", "PTR"]:
|
||||
for result in self.all_records:
|
||||
if result['name'] == record_name and result['type'] == record_type:
|
||||
if result["name"] == record_name and result["type"] == record_type:
|
||||
return result
|
||||
return False
|
||||
elif record_type in ["A", "AAAA", "MX", "NS", "TXT", "SRV"]:
|
||||
@@ -473,14 +474,14 @@ class DME2:
|
||||
value = record_value.split(" ")[3]
|
||||
else:
|
||||
value = record_value
|
||||
if result['name'] == record_name and result['type'] == record_type and result['value'] == value:
|
||||
if result["name"] == record_name and result["type"] == record_type and result["value"] == value:
|
||||
return result
|
||||
return False
|
||||
else:
|
||||
raise Exception('record_type not yet supported')
|
||||
raise Exception("record_type not yet supported")
|
||||
|
||||
def getRecords(self):
|
||||
return self.query(self.record_url, 'GET')['data']
|
||||
return self.query(self.record_url, "GET")["data"]
|
||||
|
||||
def _instMap(self, type):
|
||||
# @TODO cache this call so it is executed only once per ansible execution
|
||||
@@ -489,105 +490,106 @@ class DME2:
|
||||
|
||||
# iterate over e.g. self.getDomains() || self.getRecords()
|
||||
for result in getattr(self, f"get{type.title()}s")():
|
||||
|
||||
map[result['name']] = result['id']
|
||||
results[result['id']] = result
|
||||
map[result["name"]] = result["id"]
|
||||
results[result["id"]] = result
|
||||
|
||||
# e.g. self.domain_map || self.record_map
|
||||
setattr(self, f"{type}_map", map)
|
||||
setattr(self, f"{type}s", results) # e.g. self.domains || self.records
|
||||
|
||||
def prepareRecord(self, data):
|
||||
return json.dumps(data, separators=(',', ':'))
|
||||
return json.dumps(data, separators=(",", ":"))
|
||||
|
||||
def createRecord(self, data):
|
||||
# @TODO update the cache w/ resultant record + id when implemented
|
||||
return self.query(self.record_url, 'POST', data)
|
||||
return self.query(self.record_url, "POST", data)
|
||||
|
||||
def updateRecord(self, record_id, data):
|
||||
# @TODO update the cache w/ resultant record + id when implemented
|
||||
return self.query(f"{self.record_url}/{record_id}", 'PUT', data)
|
||||
return self.query(f"{self.record_url}/{record_id}", "PUT", data)
|
||||
|
||||
def deleteRecord(self, record_id):
|
||||
# @TODO remove record from the cache when implemented
|
||||
return self.query(f"{self.record_url}/{record_id}", 'DELETE')
|
||||
return self.query(f"{self.record_url}/{record_id}", "DELETE")
|
||||
|
||||
def getMonitor(self, record_id):
|
||||
return self.query(f"{self.monitor_url}/{record_id}", 'GET')
|
||||
return self.query(f"{self.monitor_url}/{record_id}", "GET")
|
||||
|
||||
def updateMonitor(self, record_id, data):
|
||||
return self.query(f"{self.monitor_url}/{record_id}", 'PUT', data)
|
||||
return self.query(f"{self.monitor_url}/{record_id}", "PUT", data)
|
||||
|
||||
def prepareMonitor(self, data):
|
||||
return json.dumps(data, separators=(',', ':'))
|
||||
return json.dumps(data, separators=(",", ":"))
|
||||
|
||||
def getContactList(self, contact_list_id):
|
||||
if not self.contactList_map:
|
||||
self._instMap('contactList')
|
||||
self._instMap("contactList")
|
||||
|
||||
return self.contactLists.get(contact_list_id, False)
|
||||
|
||||
def getContactlists(self):
|
||||
return self.query(self.contactList_url, 'GET')['data']
|
||||
return self.query(self.contactList_url, "GET")["data"]
|
||||
|
||||
def getContactListByName(self, name):
|
||||
if not self.contactList_map:
|
||||
self._instMap('contactList')
|
||||
self._instMap("contactList")
|
||||
|
||||
return self.getContactList(self.contactList_map.get(name, 0))
|
||||
|
||||
|
||||
# ===========================================
|
||||
# Module execution.
|
||||
#
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
module = AnsibleModule(
|
||||
argument_spec=dict(
|
||||
account_key=dict(required=True, no_log=True),
|
||||
account_secret=dict(required=True, no_log=True),
|
||||
domain=dict(required=True),
|
||||
sandbox=dict(default=False, type='bool'),
|
||||
state=dict(required=True, choices=['present', 'absent']),
|
||||
sandbox=dict(default=False, type="bool"),
|
||||
state=dict(required=True, choices=["present", "absent"]),
|
||||
record_name=dict(),
|
||||
record_type=dict(choices=[
|
||||
'A', 'AAAA', 'CNAME', 'ANAME', 'HTTPRED', 'MX', 'NS', 'PTR', 'SRV', 'TXT']),
|
||||
record_type=dict(choices=["A", "AAAA", "CNAME", "ANAME", "HTTPRED", "MX", "NS", "PTR", "SRV", "TXT"]),
|
||||
record_value=dict(),
|
||||
record_ttl=dict(default=1800, type='int'),
|
||||
monitor=dict(default=False, type='bool'),
|
||||
systemDescription=dict(default=''),
|
||||
maxEmails=dict(default=1, type='int'),
|
||||
protocol=dict(default='HTTP', choices=['TCP', 'UDP', 'HTTP', 'DNS', 'SMTP', 'HTTPS']),
|
||||
port=dict(default=80, type='int'),
|
||||
sensitivity=dict(default='Medium', choices=['Low', 'Medium', 'High']),
|
||||
record_ttl=dict(default=1800, type="int"),
|
||||
monitor=dict(default=False, type="bool"),
|
||||
systemDescription=dict(default=""),
|
||||
maxEmails=dict(default=1, type="int"),
|
||||
protocol=dict(default="HTTP", choices=["TCP", "UDP", "HTTP", "DNS", "SMTP", "HTTPS"]),
|
||||
port=dict(default=80, type="int"),
|
||||
sensitivity=dict(default="Medium", choices=["Low", "Medium", "High"]),
|
||||
contactList=dict(),
|
||||
httpFqdn=dict(),
|
||||
httpFile=dict(),
|
||||
httpQueryString=dict(),
|
||||
failover=dict(default=False, type='bool'),
|
||||
autoFailover=dict(default=False, type='bool'),
|
||||
failover=dict(default=False, type="bool"),
|
||||
autoFailover=dict(default=False, type="bool"),
|
||||
ip1=dict(),
|
||||
ip2=dict(),
|
||||
ip3=dict(),
|
||||
ip4=dict(),
|
||||
ip5=dict(),
|
||||
validate_certs=dict(default=True, type='bool'),
|
||||
validate_certs=dict(default=True, type="bool"),
|
||||
),
|
||||
required_together=[
|
||||
['record_value', 'record_ttl', 'record_type']
|
||||
],
|
||||
required_together=[["record_value", "record_ttl", "record_type"]],
|
||||
required_if=[
|
||||
['failover', True, ['autoFailover', 'port', 'protocol', 'ip1', 'ip2']],
|
||||
['monitor', True, ['port', 'protocol', 'maxEmails', 'systemDescription', 'ip1']]
|
||||
]
|
||||
["failover", True, ["autoFailover", "port", "protocol", "ip1", "ip2"]],
|
||||
["monitor", True, ["port", "protocol", "maxEmails", "systemDescription", "ip1"]],
|
||||
],
|
||||
)
|
||||
|
||||
protocols = dict(TCP=1, UDP=2, HTTP=3, DNS=4, SMTP=5, HTTPS=6)
|
||||
sensitivities = dict(Low=8, Medium=5, High=3)
|
||||
|
||||
DME = DME2(module.params["account_key"], module.params[
|
||||
"account_secret"], module.params["domain"], module.params["sandbox"], module)
|
||||
DME = DME2(
|
||||
module.params["account_key"],
|
||||
module.params["account_secret"],
|
||||
module.params["domain"],
|
||||
module.params["sandbox"],
|
||||
module,
|
||||
)
|
||||
state = module.params["state"]
|
||||
record_name = module.params["record_name"]
|
||||
record_type = module.params["record_type"]
|
||||
@@ -598,15 +600,16 @@ def main():
|
||||
domain_records = DME.getRecords()
|
||||
if not domain_records:
|
||||
module.fail_json(
|
||||
msg="The requested domain name is not accessible with this api_key; try using its ID if known.")
|
||||
msg="The requested domain name is not accessible with this api_key; try using its ID if known."
|
||||
)
|
||||
module.exit_json(changed=False, result=domain_records)
|
||||
|
||||
# Fetch existing record + Build new one
|
||||
current_record = DME.getMatchingRecord(record_name, record_type, record_value)
|
||||
new_record = {'name': record_name}
|
||||
new_record = {"name": record_name}
|
||||
for i in ["record_value", "record_type", "record_ttl"]:
|
||||
if not module.params[i] is None:
|
||||
new_record[i[len("record_"):]] = module.params[i]
|
||||
new_record[i[len("record_") :]] = module.params[i]
|
||||
# Special handling for mx record
|
||||
if new_record["type"] == "MX":
|
||||
new_record["mxLevel"] = new_record["value"].split(" ")[0]
|
||||
@@ -622,29 +625,45 @@ def main():
|
||||
# Fetch existing monitor if the A record indicates it should exist and build the new monitor
|
||||
current_monitor = dict()
|
||||
new_monitor = dict()
|
||||
if current_record and current_record['type'] == 'A' and current_record.get('monitor'):
|
||||
current_monitor = DME.getMonitor(current_record['id'])
|
||||
if current_record and current_record["type"] == "A" and current_record.get("monitor"):
|
||||
current_monitor = DME.getMonitor(current_record["id"])
|
||||
|
||||
# Build the new monitor
|
||||
for i in ['monitor', 'systemDescription', 'protocol', 'port', 'sensitivity', 'maxEmails',
|
||||
'contactList', 'httpFqdn', 'httpFile', 'httpQueryString',
|
||||
'failover', 'autoFailover', 'ip1', 'ip2', 'ip3', 'ip4', 'ip5']:
|
||||
for i in [
|
||||
"monitor",
|
||||
"systemDescription",
|
||||
"protocol",
|
||||
"port",
|
||||
"sensitivity",
|
||||
"maxEmails",
|
||||
"contactList",
|
||||
"httpFqdn",
|
||||
"httpFile",
|
||||
"httpQueryString",
|
||||
"failover",
|
||||
"autoFailover",
|
||||
"ip1",
|
||||
"ip2",
|
||||
"ip3",
|
||||
"ip4",
|
||||
"ip5",
|
||||
]:
|
||||
if module.params[i] is not None:
|
||||
if i == 'protocol':
|
||||
if i == "protocol":
|
||||
# The API requires protocol to be a numeric in the range 1-6
|
||||
new_monitor['protocolId'] = protocols[module.params[i]]
|
||||
elif i == 'sensitivity':
|
||||
new_monitor["protocolId"] = protocols[module.params[i]]
|
||||
elif i == "sensitivity":
|
||||
# The API requires sensitivity to be a numeric of 8, 5, or 3
|
||||
new_monitor[i] = sensitivities[module.params[i]]
|
||||
elif i == 'contactList':
|
||||
elif i == "contactList":
|
||||
# The module accepts either the name or the id of the contact list
|
||||
contact_list_id = module.params[i]
|
||||
if not contact_list_id.isdigit() and contact_list_id != '':
|
||||
if not contact_list_id.isdigit() and contact_list_id != "":
|
||||
contact_list = DME.getContactListByName(contact_list_id)
|
||||
if not contact_list:
|
||||
module.fail_json(msg=f"Contact list {contact_list_id} does not exist")
|
||||
contact_list_id = contact_list.get('id', '')
|
||||
new_monitor['contactListId'] = contact_list_id
|
||||
contact_list_id = contact_list.get("id", "")
|
||||
new_monitor["contactListId"] = contact_list_id
|
||||
else:
|
||||
# The module option names match the API field names
|
||||
new_monitor[i] = module.params[i]
|
||||
@@ -657,7 +676,7 @@ def main():
|
||||
# are surrounded by quotes.
|
||||
if str(current_record[i]).strip('"') != str(new_record[i]):
|
||||
record_changed = True
|
||||
new_record['id'] = str(current_record['id'])
|
||||
new_record["id"] = str(current_record["id"])
|
||||
|
||||
monitor_changed = False
|
||||
if current_monitor:
|
||||
@@ -666,19 +685,20 @@ def main():
|
||||
monitor_changed = True
|
||||
|
||||
# Follow Keyword Controlled Behavior
|
||||
if state == 'present':
|
||||
if state == "present":
|
||||
# return the record if no value is specified
|
||||
if "value" not in new_record:
|
||||
if not current_record:
|
||||
module.fail_json(
|
||||
msg=f"A record with name '{record_name}' does not exist for domain '{module.params['domain']}.'")
|
||||
msg=f"A record with name '{record_name}' does not exist for domain '{module.params['domain']}.'"
|
||||
)
|
||||
module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))
|
||||
|
||||
# create record and monitor as the record does not exist
|
||||
if not current_record:
|
||||
record = DME.createRecord(DME.prepareRecord(new_record))
|
||||
if new_monitor.get('monitor') and record_type == "A":
|
||||
monitor = DME.updateMonitor(record['id'], DME.prepareMonitor(new_monitor))
|
||||
if new_monitor.get("monitor") and record_type == "A":
|
||||
monitor = DME.updateMonitor(record["id"], DME.prepareMonitor(new_monitor))
|
||||
module.exit_json(changed=True, result=dict(record=record, monitor=monitor))
|
||||
else:
|
||||
module.exit_json(changed=True, result=dict(record=record, monitor=current_monitor))
|
||||
@@ -686,10 +706,10 @@ def main():
|
||||
# update the record
|
||||
updated = False
|
||||
if record_changed:
|
||||
DME.updateRecord(current_record['id'], DME.prepareRecord(new_record))
|
||||
DME.updateRecord(current_record["id"], DME.prepareRecord(new_record))
|
||||
updated = True
|
||||
if monitor_changed:
|
||||
DME.updateMonitor(current_monitor['recordId'], DME.prepareMonitor(new_monitor))
|
||||
DME.updateMonitor(current_monitor["recordId"], DME.prepareMonitor(new_monitor))
|
||||
updated = True
|
||||
if updated:
|
||||
module.exit_json(changed=True, result=dict(record=new_record, monitor=new_monitor))
|
||||
@@ -697,20 +717,19 @@ def main():
|
||||
# return the record (no changes)
|
||||
module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))
|
||||
|
||||
elif state == 'absent':
|
||||
elif state == "absent":
|
||||
changed = False
|
||||
# delete the record (and the monitor/failover) if it exists
|
||||
if current_record:
|
||||
DME.deleteRecord(current_record['id'])
|
||||
DME.deleteRecord(current_record["id"])
|
||||
module.exit_json(changed=True)
|
||||
|
||||
# record does not exist, return w/o change.
|
||||
module.exit_json(changed=changed)
|
||||
|
||||
else:
|
||||
module.fail_json(
|
||||
msg=f"'{state}' is an unknown value for the state argument")
|
||||
module.fail_json(msg=f"'{state}' is an unknown value for the state argument")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user