Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright Ansible Project
4 #
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: dnsimple
12 short_description: Interface with dnsimple.com (a DNS hosting service)
13 description:
14 - 'Manages domains and records using the DNSimple API, see the docs: U(http://developer.dnsimple.com/).'
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 account_email:
24 description:
25 - Account email. If omitted, the environment variables E(DNSIMPLE_EMAIL) and E(DNSIMPLE_API_TOKEN) are looked for.
26 - 'If those variables are not found, a C(.dnsimple) file is looked for, see: U(https://github.com/mikemaccana/dnsimple-python#getting-started).'
27 - C(.dnsimple) config files are only supported in dnsimple-python<2.0.0.
28 type: str
29 account_api_token:
30 description:
31 - Account API token. See O(account_email) for more information.
32 type: str
33 domain:
34 description:
35 - Domain to work with. Can be the domain name (for example V(mydomain.com)) or the numeric ID of the domain in DNSimple.
36 - If omitted, a list of domains is returned.
37 - If domain is present but the domain does not exist, it is created.
38 type: str
39 record:
40 description:
41 - Record to add, if blank a record for the domain is created, supports the wildcard (*).
42 type: str
43 record_ids:
44 description:
45 - List of records to ensure they either exist or do not exist.
46 type: list
47 elements: str
48 type:
49 description:
50 - The type of DNS record to create.
51 choices:
52 - A
53 - ALIAS
54 - CNAME
55 - MX
56 - SPF
57 - URL
58 - TXT
59 - NS
60 - SRV
61 - NAPTR
62 - PTR
63 - AAAA
64 - SSHFP
65 - HINFO
66 - POOL
67 - CAA
68 type: str
69 ttl:
70 description:
71 - The TTL to give the new record in seconds.
72 default: 3600
73 type: int
74 value:
75 description:
76 - Record value.
77 - Must be specified when trying to ensure a record exists.
78 type: str
79 priority:
80 description:
81 - Record priority.
82 type: int
83 state:
84 description:
85 - Whether the record should exist or not.
86 choices: ['present', 'absent']
87 default: present
88 type: str
89 solo:
90 description:
91 - Whether the record should be the only one for that record type and record name.
92 - Only use with O(state) is set to V(present) on a record.
93 type: 'bool'
94 default: false
95 sandbox:
96 description:
97 - Use the DNSimple sandbox environment.
98 - Requires a dedicated account in the dnsimple sandbox environment.
99 - Check U(https://developer.dnsimple.com/sandbox/) for more information.
100 type: 'bool'
101 default: false
102 version_added: 3.5.0
103 requirements:
104 - "dnsimple >= 2.0.0"
105 author: "Alex Coomans (@drcapulet)"
106 """
107
108 EXAMPLES = r"""
109 - name: Authenticate using email and API token and fetch all domains
110 community.general.dnsimple:
111 account_email: [email protected]
112 account_api_token: dummyapitoken
113 delegate_to: localhost
114
115 - name: Delete a domain
116 community.general.dnsimple:
117 domain: my.com
118 state: absent
119 delegate_to: localhost
120
121 - name: Create a test.my.com A record to point to 127.0.0.1
122 community.general.dnsimple:
123 domain: my.com
124 record: test
125 type: A
126 value: 127.0.0.1
127 delegate_to: localhost
128 register: record
129
130 - name: Delete record using record_ids
131 community.general.dnsimple:
132 domain: my.com
133 record_ids: '{{ record["id"] }}'
134 state: absent
135 delegate_to: localhost
136
137 - name: Create a my.com CNAME record to example.com
138 community.general.dnsimple:
139 domain: my.com
140 record: ''
141 type: CNAME
142 value: example.com
143 state: present
144 delegate_to: localhost
145
146 - name: Change TTL value for a record
147 community.general.dnsimple:
148 domain: my.com
149 record: ''
150 type: CNAME
151 value: example.com
152 ttl: 600
153 state: present
154 delegate_to: localhost
155
156 - name: Delete the record
157 community.general.dnsimple:
158 domain: my.com
159 record: ''
160 type: CNAME
161 value: example.com
162 state: absent
163 delegate_to: localhost
164 """
165
166 RETURN = r"""#"""
167
168 import re
169 import traceback
170
171 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
172
173
174 class DNSimpleV2:
175 """class which uses dnsimple-python >= 2"""
176
177 def __init__(self, account_email, account_api_token, sandbox, module):
178 """init"""
179 self.module = module
180 self.account_email = account_email
181 self.account_api_token = account_api_token
182 self.sandbox = sandbox
183 self.pagination_per_page = 30
184 self.dnsimple_client()
185 self.dnsimple_account()
186
187 def dnsimple_client(self):
188 """creates a dnsimple client object"""
189 if self.account_email and self.account_api_token:
190 client = Client(
191 sandbox=self.sandbox,
192 email=self.account_email,
193 access_token=self.account_api_token,
194 user_agent="ansible/community.general",
195 )
196 else:
197 msg = (
198 "Option account_email or account_api_token not provided. "
199 "Dnsimple authentication with a .dnsimple config file is not "
200 "supported with dnsimple-python>=2.0.0"
201 )
202 raise DNSimpleException(msg)
203 client.identity.whoami()
204 self.client = client
205
206 def dnsimple_account(self):
207 """select a dnsimple account. If a user token is used for authentication,
208 this user must only have access to a single account"""
209 account = self.client.identity.whoami().data.account
210 # user supplied a user token instead of account api token
211 if not account:
212 accounts = Accounts(self.client).list_accounts().data
213 if len(accounts) != 1:
214 msg = (
215 "The provided dnsimple token is a user token with multiple accounts."
216 "Use an account token or a user token with access to a single account."
217 "See https://support.dnsimple.com/articles/api-access-token/"
218 )
219 raise DNSimpleException(msg)
220 account = accounts[0]
221 self.account = account
222
223 def get_all_domains(self):
224 """returns a list of all domains"""
225 domain_list = self._get_paginated_result(self.client.domains.list_domains, account_id=self.account.id)
226 return [d.__dict__ for d in domain_list]
227
228 def get_domain(self, domain):
229 """returns a single domain by name or id"""
230 try:
231 dr = self.client.domains.get_domain(self.account.id, domain).data.__dict__
232 except DNSimpleException as e:
233 exception_string = str(e.message)
234 if re.match(r"^Domain .+ not found$", exception_string):
235 dr = None
236 else:
237 raise
238 return dr
239
240 def create_domain(self, domain):
241 """create a single domain"""
242 return self.client.domains.create_domain(self.account.id, domain).data.__dict__
243
244 def delete_domain(self, domain):
245 """delete a single domain"""
246 self.client.domains.delete_domain(self.account.id, domain)
247
248 def get_records(self, zone, dnsimple_filter=None):
249 """return dns resource records which match a specified filter"""
250 records_list = self._get_paginated_result(
251 self.client.zones.list_records, account_id=self.account.id, zone=zone, filter=dnsimple_filter
252 )
253 return [d.__dict__ for d in records_list]
254
255 def delete_record(self, domain, rid):
256 """delete a single dns resource record"""
257 self.client.zones.delete_record(self.account.id, domain, rid)
258
259 def update_record(self, domain, rid, ttl=None, priority=None):
260 """update a single dns resource record"""
261 zr = ZoneRecordUpdateInput(ttl=ttl, priority=priority)
262 result = self.client.zones.update_record(self.account.id, str(domain), str(rid), zr).data.__dict__
263 return result
264
265 def create_record(self, domain, name, record_type, content, ttl=None, priority=None):
266 """create a single dns resource record"""
267 zr = ZoneRecordInput(name=name, type=record_type, content=content, ttl=ttl, priority=priority)
268 return self.client.zones.create_record(self.account.id, str(domain), zr).data.__dict__
269
270 def _get_paginated_result(self, operation, **options):
271 """return all results of a paginated api response"""
272 records_pagination = operation(per_page=self.pagination_per_page, **options).pagination
273 result_list = []
274 for page in range(1, records_pagination.total_pages + 1):
275 page_data = operation(per_page=self.pagination_per_page, page=page, **options).data
276 result_list.extend(page_data)
277 return result_list
278
279
280 DNSIMPLE_IMP_ERR = []
281 HAS_DNSIMPLE = False
282 try:
283 # try to import dnsimple >= 2.0.0
284 from dnsimple import Client, DNSimpleException
285 from dnsimple.service import Accounts
286 from dnsimple.struct.zone_record import ZoneRecordInput, ZoneRecordUpdateInput
287 from dnsimple.version import version as dnsimple_version
288
289 HAS_DNSIMPLE = True
290 except ImportError:
291 DNSIMPLE_IMP_ERR.append(traceback.format_exc())
292
293 from ansible.module_utils.basic import AnsibleModule, env_fallback, missing_required_lib
294
295
296 def main():
297 module = AnsibleModule(
298 argument_spec=dict(
299 account_email=dict(type="str", fallback=(env_fallback, ["DNSIMPLE_EMAIL"])),
300 account_api_token=dict(type="str", no_log=True, fallback=(env_fallback, ["DNSIMPLE_API_TOKEN"])),
301 domain=dict(type="str"),
302 record=dict(type="str"),
303 record_ids=dict(type="list", elements="str"),
304 type=dict(
305 type="str",
306 choices=[
307 "A",
308 "ALIAS",
309 "CNAME",
310 "MX",
311 "SPF",
312 "URL",
313 "TXT",
314 "NS",
315 "SRV",
316 "NAPTR",
317 "PTR",
318 "AAAA",
319 "SSHFP",
320 "HINFO",
321 "POOL",
322 "CAA",
323 ],
324 ),
325 ttl=dict(type="int", default=3600),
326 value=dict(type="str"),
327 priority=dict(type="int"),
328 state=dict(type="str", choices=["present", "absent"], default="present"),
329 solo=dict(type="bool", default=False),
330 sandbox=dict(type="bool", default=False),
331 ),
332 required_together=[["record", "value"]],
333 supports_check_mode=True,
334 )
335
336 if not HAS_DNSIMPLE:
337 module.fail_json(msg=missing_required_lib("dnsimple"), exception=DNSIMPLE_IMP_ERR[0])
338
339 account_email = module.params.get("account_email")
340 account_api_token = module.params.get("account_api_token")
341 domain = module.params.get("domain")
342 record = module.params.get("record")
343 record_ids = module.params.get("record_ids")
344 record_type = module.params.get("type")
345 ttl = module.params.get("ttl")
346 value = module.params.get("value")
347 priority = module.params.get("priority")
348 state = module.params.get("state")
349 is_solo = module.params.get("solo")
350 sandbox = module.params.get("sandbox")
351
352 DNSIMPLE_MAJOR_VERSION = LooseVersion(dnsimple_version).version[0]
353
354 try:
355 if DNSIMPLE_MAJOR_VERSION < 2:
356 module.fail_json(
357 msg="Support for python-dnsimple < 2 has been removed in community.general 5.0.0. Update python-dnsimple to version >= 2.0.0."
358 )
359 ds = DNSimpleV2(account_email, account_api_token, sandbox, module)
360 # Let's figure out what operation we want to do
361 # No domain, return a list
362 if not domain:
363 all_domains = ds.get_all_domains()
364 module.exit_json(changed=False, result=all_domains)
365
366 # Domain & No record
367 if record is None and not record_ids:
368 if domain.isdigit():
369 typed_domain = int(domain)
370 else:
371 typed_domain = str(domain)
372 dr = ds.get_domain(typed_domain)
373 # domain does not exist
374 if state == "present":
375 if dr:
376 module.exit_json(changed=False, result=dr)
377 else:
378 if module.check_mode:
379 module.exit_json(changed=True)
380 else:
381 response = ds.create_domain(domain)
382 module.exit_json(changed=True, result=response)
383 # state is absent
384 else:
385 if dr:
386 if not module.check_mode:
387 ds.delete_domain(domain)
388 module.exit_json(changed=True)
389 else:
390 module.exit_json(changed=False)
391
392 # need the not none check since record could be an empty string
393 if record is not None:
394 if not record_type:
395 module.fail_json(msg="Missing the record type")
396 if not value:
397 module.fail_json(msg="Missing the record value")
398
399 records_list = ds.get_records(domain, dnsimple_filter={"name": record})
400 rr = next(
401 (r for r in records_list if r["name"] == record and r["type"] == record_type and r["content"] == value),
402 None,
403 )
404 if state == "present":
405 changed = False
406 if is_solo:
407 # delete any records that have the same name and record type
408 same_type = [r["id"] for r in records_list if r["name"] == record and r["type"] == record_type]
409 if rr:
410 same_type = [rid for rid in same_type if rid != rr["id"]]
411 if same_type:
412 if not module.check_mode:
413 for rid in same_type:
414 ds.delete_record(domain, rid)
415 changed = True
416 if rr:
417 # check if we need to update
418 if rr["ttl"] != ttl or rr["priority"] != priority:
419 if module.check_mode:
420 module.exit_json(changed=True)
421 else:
422 response = ds.update_record(domain, rr["id"], ttl, priority)
423 module.exit_json(changed=True, result=response)
424 else:
425 module.exit_json(changed=changed, result=rr)
426 else:
427 # create it
428 if module.check_mode:
429 module.exit_json(changed=True)
430 else:
431 response = ds.create_record(domain, record, record_type, value, ttl, priority)
432 module.exit_json(changed=True, result=response)
433 # state is absent
434 else:
435 if rr:
436 if not module.check_mode:
437 ds.delete_record(domain, rr["id"])
438 module.exit_json(changed=True)
439 else:
440 module.exit_json(changed=False)
441
442 # Make sure these record_ids either all exist or none
443 if record_ids:
444 current_records = ds.get_records(domain, dnsimple_filter=None)
445 current_record_ids = [str(d["id"]) for d in current_records]
446 wanted_record_ids = [str(r) for r in record_ids]
447 if state == "present":
448 difference = list(set(wanted_record_ids) - set(current_record_ids))
449 if difference:
450 module.fail_json(msg=f"Missing the following records: {difference}")
451 else:
452 module.exit_json(changed=False)
453 # state is absent
454 else:
455 difference = list(set(wanted_record_ids) & set(current_record_ids))
456 if difference:
457 if not module.check_mode:
458 for rid in difference:
459 ds.delete_record(domain, rid)
460 module.exit_json(changed=True)
461 else:
462 module.exit_json(changed=False)
463
464 except DNSimpleException as e:
465 if DNSIMPLE_MAJOR_VERSION > 1:
466 module.fail_json(msg=f"DNSimple exception: {e.message}")
467 else:
468 module.fail_json(msg=f"DNSimple exception: {e.args[0]['message']}")
469 module.fail_json(msg="Unknown what you wanted me to do")
470
471
472 if __name__ == "__main__":
473 main()