Debian Codegraph @

ansible_collections/community/general/plugins/modules/dnsmadeeasy.py

raw
1 #!/usr/bin/python
2
3 # Copyright Ansible Project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: dnsmadeeasy
11 short_description: Interface with dnsmadeeasy.com (a DNS hosting service)
12 description:
13 - 'Manages DNS records using the v2 REST API of the DNS Made Easy service. It handles records only; there is no manipulation
14 of domains or monitor/account support yet. See: U(https://www.dnsmadeeasy.com/integration/restapi/).'
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 account_key:
24 description:
25 - Account API Key.
26 required: true
27 type: str
28
29 account_secret:
30 description:
31 - Account Secret Key.
32 required: true
33 type: str
34
35 domain:
36 description:
37 - Domain to work with. Can be the domain name (for example V(mydomain.com)) or the numeric ID of the domain in DNS Made
38 Easy (for example V(839989)) for faster resolution.
39 required: true
40 type: str
41
42 sandbox:
43 description:
44 - Decides if the sandbox API should be used. Otherwise (default) the production API of DNS Made Easy is used.
45 type: bool
46 default: false
47
48 record_name:
49 description:
50 - Record name to get/create/delete/update. If O(record_name) is not specified; all records for the domain are returned
51 in "result" regardless of the state argument.
52 type: str
53
54 record_type:
55 description:
56 - Record type.
57 choices: ['A', 'AAAA', 'CNAME', 'ANAME', 'HTTPRED', 'MX', 'NS', 'PTR', 'SRV', 'TXT']
58 type: str
59
60 record_value:
61 description:
62 - 'Record value. HTTPRED: <redirection URL>, MX: <priority> <target name>, NS: <name server>, PTR: <target name>, SRV:
63 <priority> <weight> <port> <target name>, TXT: <text value>".'
64 - If O(record_value) is not specified; no changes are made and the record is returned in RV(ignore:result) (in other
65 words, this module can be used to fetch a record's current ID, type, and TTL).
66 type: str
67
68 record_ttl:
69 description:
70 - Record's "Time-To-Live". Number of seconds the record remains cached in DNS servers.
71 default: 1800
72 type: int
73
74 state:
75 description:
76 - Whether the record should exist or not.
77 required: true
78 choices: ['present', 'absent']
79 type: str
80
81 validate_certs:
82 description:
83 - If V(false), SSL certificates are not validated. This should only be used on personally controlled sites using self-signed
84 certificates.
85 type: bool
86 default: true
87
88 monitor:
89 description:
90 - If V(true), add or change the monitor. This is applicable only for A records.
91 type: bool
92 default: false
93
94 systemDescription:
95 description:
96 - Description used by the monitor.
97 default: ''
98 type: str
99
100 maxEmails:
101 description:
102 - Number of emails sent to the contact list by the monitor.
103 default: 1
104 type: int
105
106 protocol:
107 description:
108 - Protocol used by the monitor.
109 default: 'HTTP'
110 choices: ['TCP', 'UDP', 'HTTP', 'DNS', 'SMTP', 'HTTPS']
111 type: str
112
113 port:
114 description:
115 - Port used by the monitor.
116 default: 80
117 type: int
118
119 sensitivity:
120 description:
121 - Number of checks the monitor performs before a failover occurs where Low = 8, Medium = 5,and High = 3.
122 default: 'Medium'
123 choices: ['Low', 'Medium', 'High']
124 type: str
125
126 contactList:
127 description:
128 - Name or ID of the contact list that the monitor notifies.
129 - The default V('') means the Account Owner.
130 type: str
131
132 httpFqdn:
133 description:
134 - The fully qualified domain name used by the monitor.
135 type: str
136
137 httpFile:
138 description:
139 - The file at the Fqdn that the monitor queries for HTTP or HTTPS.
140 type: str
141
142 httpQueryString:
143 description:
144 - The string in the httpFile that the monitor queries for HTTP or HTTPS.
145 type: str
146
147 failover:
148 description:
149 - If V(true), add or change the failover. This is applicable only for A records.
150 type: bool
151 default: false
152
153 autoFailover:
154 description:
155 - If true, fallback to the primary IP address is manual after a failover.
156 - If false, fallback to the primary IP address is automatic after a failover.
157 type: bool
158 default: false
159
160 ip1:
161 description:
162 - Primary IP address for the failover.
163 - Required if adding or changing the monitor or failover.
164 type: str
165
166 ip2:
167 description:
168 - Secondary IP address for the failover.
169 - Required if adding or changing the failover.
170 type: str
171
172 ip3:
173 description:
174 - Tertiary IP address for the failover.
175 type: str
176
177 ip4:
178 description:
179 - Quaternary IP address for the failover.
180 type: str
181
182 ip5:
183 description:
184 - Quinary IP address for the failover.
185 type: str
186
187 notes:
188 - The DNS Made Easy service requires that machines interacting with the API have the proper time and timezone set. Be sure
189 you are within a few seconds of actual time by using NTP.
190 - This module returns record(s) and monitor(s) in the RV(ignore:result) element when O(state=present). These values can
191 be be registered and used in your playbooks.
192 - Only A records can have a O(monitor) or O(failover).
193 - To add failover, the O(failover), O(autoFailover), O(port), O(protocol), O(ip1), and O(ip2) options are required.
194 - To add monitor, the O(monitor), O(port), O(protocol), O(maxEmails), O(systemDescription), and O(ip1) options are required.
195 - The options O(monitor) and O(failover) share O(port), O(protocol), and O(ip1) options.
196 requirements: [hashlib, hmac]
197 author: "Brice Burgess (@briceburg)"
198 """
199
200 EXAMPLES = r"""
201 - name: Fetch my.com domain records
202 community.general.dnsmadeeasy:
203 account_key: key
204 account_secret: secret
205 domain: my.com
206 state: present
207 register: response
208
209 - name: Create a record
210 community.general.dnsmadeeasy:
211 account_key: key
212 account_secret: secret
213 domain: my.com
214 state: present
215 record_name: test
216 record_type: A
217 record_value: 127.0.0.1
218
219 - name: Update the previously created record
220 community.general.dnsmadeeasy:
221 account_key: key
222 account_secret: secret
223 domain: my.com
224 state: present
225 record_name: test
226 record_value: 192.0.2.23
227
228 - name: Fetch a specific record
229 community.general.dnsmadeeasy:
230 account_key: key
231 account_secret: secret
232 domain: my.com
233 state: present
234 record_name: test
235 register: response
236
237 - name: Delete a record
238 community.general.dnsmadeeasy:
239 account_key: key
240 account_secret: secret
241 domain: my.com
242 record_type: A
243 state: absent
244 record_name: test
245
246 - name: Add a failover
247 community.general.dnsmadeeasy:
248 account_key: key
249 account_secret: secret
250 domain: my.com
251 state: present
252 record_name: test
253 record_type: A
254 record_value: 127.0.0.1
255 failover: true
256 ip1: 127.0.0.2
257 ip2: 127.0.0.3
258
259 - name: Add a failover
260 community.general.dnsmadeeasy:
261 account_key: key
262 account_secret: secret
263 domain: my.com
264 state: present
265 record_name: test
266 record_type: A
267 record_value: 127.0.0.1
268 failover: true
269 ip1: 127.0.0.2
270 ip2: 127.0.0.3
271 ip3: 127.0.0.4
272 ip4: 127.0.0.5
273 ip5: 127.0.0.6
274
275 - name: Add a monitor
276 community.general.dnsmadeeasy:
277 account_key: key
278 account_secret: secret
279 domain: my.com
280 state: present
281 record_name: test
282 record_type: A
283 record_value: 127.0.0.1
284 monitor: true
285 ip1: 127.0.0.2
286 protocol: HTTP # default
287 port: 80 # default
288 maxEmails: 1
289 systemDescription: Monitor Test A record
290 contactList: my contact list
291
292 - name: Add a monitor with http options
293 community.general.dnsmadeeasy:
294 account_key: key
295 account_secret: secret
296 domain: my.com
297 state: present
298 record_name: test
299 record_type: A
300 record_value: 127.0.0.1
301 monitor: true
302 ip1: 127.0.0.2
303 protocol: HTTP # default
304 port: 80 # default
305 maxEmails: 1
306 systemDescription: Monitor Test A record
307 contactList: 1174 # contact list id
308 httpFqdn: http://my.com
309 httpFile: example
310 httpQueryString: some string
311
312 - name: Add a monitor and a failover
313 community.general.dnsmadeeasy:
314 account_key: key
315 account_secret: secret
316 domain: my.com
317 state: present
318 record_name: test
319 record_type: A
320 record_value: 127.0.0.1
321 failover: true
322 ip1: 127.0.0.2
323 ip2: 127.0.0.3
324 monitor: true
325 protocol: HTTPS
326 port: 443
327 maxEmails: 1
328 systemDescription: monitoring my.com status
329 contactList: emergencycontacts
330
331 - name: Remove a failover
332 community.general.dnsmadeeasy:
333 account_key: key
334 account_secret: secret
335 domain: my.com
336 state: present
337 record_name: test
338 record_type: A
339 record_value: 127.0.0.1
340 failover: false
341
342 - name: Remove a monitor
343 community.general.dnsmadeeasy:
344 account_key: key
345 account_secret: secret
346 domain: my.com
347 state: present
348 record_name: test
349 record_type: A
350 record_value: 127.0.0.1
351 monitor: false
352 """
353
354 # ============================================
355 # DNSMadeEasy module specific support methods.
356 #
357
358 import hashlib
359 import hmac
360 import json
361 import locale
362 from time import gmtime, strftime
363 from urllib.parse import urlencode
364
365 from ansible.module_utils.basic import AnsibleModule
366 from ansible.module_utils.urls import fetch_url
367
368
369 class DME2:
370 def __init__(self, apikey, secret, domain, sandbox, module):
371 self.module = module
372
373 self.api = apikey
374 self.secret = secret
375
376 if sandbox:
377 self.baseurl = "https://api.sandbox.dnsmadeeasy.com/V2.0/"
378 self.module.warn(warning=f"Sandbox is enabled. All actions are made against the URL {self.baseurl}")
379 else:
380 self.baseurl = "https://api.dnsmadeeasy.com/V2.0/"
381
382 self.domain = str(domain)
383 self.domain_map = None # ["domain_name"] => ID
384 self.record_map = None # ["record_name"] => ID
385 self.records = None # ["record_ID"] => <record>
386 self.all_records = None
387 self.contactList_map = None # ["contactList_name"] => ID
388
389 # Lookup the domain ID if passed as a domain name vs. ID
390 if not self.domain.isdigit():
391 self.domain = self.getDomainByName(self.domain)["id"]
392
393 self.record_url = f"dns/managed/{self.domain}/records"
394 self.monitor_url = "monitor"
395 self.contactList_url = "contactList"
396
397 def _headers(self):
398 currTime = self._get_date()
399 hashstring = self._create_hash(currTime)
400 headers = {
401 "x-dnsme-apiKey": self.api,
402 "x-dnsme-hmac": hashstring,
403 "x-dnsme-requestDate": currTime,
404 "content-type": "application/json",
405 }
406 return headers
407
408 def _get_date(self):
409 locale.setlocale(locale.LC_TIME, "C")
410 return strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())
411
412 def _create_hash(self, rightnow):
413 return hmac.new(self.secret.encode(), rightnow.encode(), hashlib.sha1).hexdigest()
414
415 def query(self, resource, method, data=None):
416 url = self.baseurl + resource
417 if data and not isinstance(data, str):
418 data = urlencode(data)
419
420 response, info = fetch_url(self.module, url, data=data, method=method, headers=self._headers())
421 if info["status"] not in (200, 201, 204):
422 self.module.fail_json(msg=f"{url} returned {info['status']}, with body: {info['msg']}")
423
424 try:
425 return json.load(response)
426 except Exception:
427 return {}
428
429 def getDomain(self, domain_id):
430 if not self.domain_map:
431 self._instMap("domain")
432
433 return self.domains.get(domain_id, False)
434
435 def getDomainByName(self, domain_name):
436 if not self.domain_map:
437 self._instMap("domain")
438
439 return self.getDomain(self.domain_map.get(domain_name, 0))
440
441 def getDomains(self):
442 return self.query("dns/managed", "GET")["data"]
443
444 def getRecord(self, record_id):
445 if not self.record_map:
446 self._instMap("record")
447
448 return self.records.get(record_id, False)
449
450 # Try to find a single record matching this one.
451 # How we do this depends on the type of record. For instance, there
452 # can be several MX records for a single record_name while there can
453 # only be a single CNAME for a particular record_name. Note also that
454 # there can be several records with different types for a single name.
455 def getMatchingRecord(self, record_name, record_type, record_value):
456 # Get all the records if not already cached
457 if not self.all_records:
458 self.all_records = self.getRecords()
459
460 if record_type in ["CNAME", "ANAME", "HTTPRED", "PTR"]:
461 for result in self.all_records:
462 if result["name"] == record_name and result["type"] == record_type:
463 return result
464 return False
465 elif record_type in ["A", "AAAA", "MX", "NS", "TXT", "SRV"]:
466 for result in self.all_records:
467 if record_type == "MX":
468 value = record_value.split(" ")[1]
469 # Note that TXT records are surrounded by quotes in the API response.
470 elif record_type == "TXT":
471 value = f'"{record_value}"'
472 elif record_type == "SRV":
473 value = record_value.split(" ")[3]
474 else:
475 value = record_value
476 if result["name"] == record_name and result["type"] == record_type and result["value"] == value:
477 return result
478 return False
479 else:
480 raise Exception("record_type not yet supported")
481
482 def getRecords(self):
483 return self.query(self.record_url, "GET")["data"]
484
485 def _instMap(self, type):
486 # @TODO cache this call so it is executed only once per ansible execution
487 map = {}
488 results = {}
489
490 # iterate over e.g. self.getDomains() || self.getRecords()
491 for result in getattr(self, f"get{type.title()}s")():
492 map[result["name"]] = result["id"]
493 results[result["id"]] = result
494
495 # e.g. self.domain_map || self.record_map
496 setattr(self, f"{type}_map", map)
497 setattr(self, f"{type}s", results) # e.g. self.domains || self.records
498
499 def prepareRecord(self, data):
500 return json.dumps(data, separators=(",", ":"))
501
502 def createRecord(self, data):
503 # @TODO update the cache w/ resultant record + id when implemented
504 return self.query(self.record_url, "POST", data)
505
506 def updateRecord(self, record_id, data):
507 # @TODO update the cache w/ resultant record + id when implemented
508 return self.query(f"{self.record_url}/{record_id}", "PUT", data)
509
510 def deleteRecord(self, record_id):
511 # @TODO remove record from the cache when implemented
512 return self.query(f"{self.record_url}/{record_id}", "DELETE")
513
514 def getMonitor(self, record_id):
515 return self.query(f"{self.monitor_url}/{record_id}", "GET")
516
517 def updateMonitor(self, record_id, data):
518 return self.query(f"{self.monitor_url}/{record_id}", "PUT", data)
519
520 def prepareMonitor(self, data):
521 return json.dumps(data, separators=(",", ":"))
522
523 def getContactList(self, contact_list_id):
524 if not self.contactList_map:
525 self._instMap("contactList")
526
527 return self.contactLists.get(contact_list_id, False)
528
529 def getContactlists(self):
530 return self.query(self.contactList_url, "GET")["data"]
531
532 def getContactListByName(self, name):
533 if not self.contactList_map:
534 self._instMap("contactList")
535
536 return self.getContactList(self.contactList_map.get(name, 0))
537
538
539 # ===========================================
540 # Module execution.
541 #
542
543
544 def main():
545 module = AnsibleModule(
546 argument_spec=dict(
547 account_key=dict(required=True, no_log=True),
548 account_secret=dict(required=True, no_log=True),
549 domain=dict(required=True),
550 sandbox=dict(default=False, type="bool"),
551 state=dict(required=True, choices=["present", "absent"]),
552 record_name=dict(),
553 record_type=dict(choices=["A", "AAAA", "CNAME", "ANAME", "HTTPRED", "MX", "NS", "PTR", "SRV", "TXT"]),
554 record_value=dict(),
555 record_ttl=dict(default=1800, type="int"),
556 monitor=dict(default=False, type="bool"),
557 systemDescription=dict(default=""),
558 maxEmails=dict(default=1, type="int"),
559 protocol=dict(default="HTTP", choices=["TCP", "UDP", "HTTP", "DNS", "SMTP", "HTTPS"]),
560 port=dict(default=80, type="int"),
561 sensitivity=dict(default="Medium", choices=["Low", "Medium", "High"]),
562 contactList=dict(),
563 httpFqdn=dict(),
564 httpFile=dict(),
565 httpQueryString=dict(),
566 failover=dict(default=False, type="bool"),
567 autoFailover=dict(default=False, type="bool"),
568 ip1=dict(),
569 ip2=dict(),
570 ip3=dict(),
571 ip4=dict(),
572 ip5=dict(),
573 validate_certs=dict(default=True, type="bool"),
574 ),
575 required_together=[["record_value", "record_ttl", "record_type"]],
576 required_if=[
577 ["failover", True, ["autoFailover", "port", "protocol", "ip1", "ip2"]],
578 ["monitor", True, ["port", "protocol", "maxEmails", "systemDescription", "ip1"]],
579 ],
580 )
581
582 protocols = dict(TCP=1, UDP=2, HTTP=3, DNS=4, SMTP=5, HTTPS=6)
583 sensitivities = dict(Low=8, Medium=5, High=3)
584
585 DME = DME2(
586 module.params["account_key"],
587 module.params["account_secret"],
588 module.params["domain"],
589 module.params["sandbox"],
590 module,
591 )
592 state = module.params["state"]
593 record_name = module.params["record_name"]
594 record_type = module.params["record_type"]
595 record_value = module.params["record_value"]
596
597 # Follow Keyword Controlled Behavior
598 if record_name is None:
599 domain_records = DME.getRecords()
600 if not domain_records:
601 module.fail_json(
602 msg="The requested domain name is not accessible with this api_key; try using its ID if known."
603 )
604 module.exit_json(changed=False, result=domain_records)
605
606 # Fetch existing record + Build new one
607 current_record = DME.getMatchingRecord(record_name, record_type, record_value)
608 new_record = {"name": record_name}
609 for i in ["record_value", "record_type", "record_ttl"]:
610 if module.params[i] is not None:
611 new_record[i[len("record_") :]] = module.params[i]
612 # Special handling for mx record
613 if new_record["type"] == "MX":
614 new_record["mxLevel"] = new_record["value"].split(" ")[0]
615 new_record["value"] = new_record["value"].split(" ")[1]
616
617 # Special handling for SRV records
618 if new_record["type"] == "SRV":
619 new_record["priority"] = new_record["value"].split(" ")[0]
620 new_record["weight"] = new_record["value"].split(" ")[1]
621 new_record["port"] = new_record["value"].split(" ")[2]
622 new_record["value"] = new_record["value"].split(" ")[3]
623
624 # Fetch existing monitor if the A record indicates it should exist and build the new monitor
625 current_monitor = dict()
626 new_monitor = dict()
627 if current_record and current_record["type"] == "A" and current_record.get("monitor"):
628 current_monitor = DME.getMonitor(current_record["id"])
629
630 # Build the new monitor
631 for i in [
632 "monitor",
633 "systemDescription",
634 "protocol",
635 "port",
636 "sensitivity",
637 "maxEmails",
638 "contactList",
639 "httpFqdn",
640 "httpFile",
641 "httpQueryString",
642 "failover",
643 "autoFailover",
644 "ip1",
645 "ip2",
646 "ip3",
647 "ip4",
648 "ip5",
649 ]:
650 if module.params[i] is not None:
651 if i == "protocol":
652 # The API requires protocol to be a numeric in the range 1-6
653 new_monitor["protocolId"] = protocols[module.params[i]]
654 elif i == "sensitivity":
655 # The API requires sensitivity to be a numeric of 8, 5, or 3
656 new_monitor[i] = sensitivities[module.params[i]]
657 elif i == "contactList":
658 # The module accepts either the name or the id of the contact list
659 contact_list_id = module.params[i]
660 if not contact_list_id.isdigit() and contact_list_id != "":
661 contact_list = DME.getContactListByName(contact_list_id)
662 if not contact_list:
663 module.fail_json(msg=f"Contact list {contact_list_id} does not exist")
664 contact_list_id = contact_list.get("id", "")
665 new_monitor["contactListId"] = contact_list_id
666 else:
667 # The module option names match the API field names
668 new_monitor[i] = module.params[i]
669
670 # Compare new record against existing one
671 record_changed = False
672 if current_record:
673 for i in new_record:
674 # Remove leading and trailing quote character from values because TXT records
675 # are surrounded by quotes.
676 if str(current_record[i]).strip('"') != str(new_record[i]):
677 record_changed = True
678 new_record["id"] = str(current_record["id"])
679
680 monitor_changed = False
681 if current_monitor:
682 for i in new_monitor:
683 if str(current_monitor.get(i)) != str(new_monitor[i]):
684 monitor_changed = True
685
686 # Follow Keyword Controlled Behavior
687 if state == "present":
688 # return the record if no value is specified
689 if "value" not in new_record:
690 if not current_record:
691 module.fail_json(
692 msg=f"A record with name '{record_name}' does not exist for domain '{module.params['domain']}.'"
693 )
694 module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))
695
696 # create record and monitor as the record does not exist
697 if not current_record:
698 record = DME.createRecord(DME.prepareRecord(new_record))
699 if new_monitor.get("monitor") and record_type == "A":
700 monitor = DME.updateMonitor(record["id"], DME.prepareMonitor(new_monitor))
701 module.exit_json(changed=True, result=dict(record=record, monitor=monitor))
702 else:
703 module.exit_json(changed=True, result=dict(record=record, monitor=current_monitor))
704
705 # update the record
706 updated = False
707 if record_changed:
708 DME.updateRecord(current_record["id"], DME.prepareRecord(new_record))
709 updated = True
710 if monitor_changed:
711 DME.updateMonitor(current_monitor["recordId"], DME.prepareMonitor(new_monitor))
712 updated = True
713 if updated:
714 module.exit_json(changed=True, result=dict(record=new_record, monitor=new_monitor))
715
716 # return the record (no changes)
717 module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))
718
719 elif state == "absent":
720 changed = False
721 # delete the record (and the monitor/failover) if it exists
722 if current_record:
723 DME.deleteRecord(current_record["id"])
724 module.exit_json(changed=True)
725
726 # record does not exist, return w/o change.
727 module.exit_json(changed=changed)
728
729 else:
730 module.fail_json(msg=f"'{state}' is an unknown value for the state argument")
731
732
733 if __name__ == "__main__":
734 main()