Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_dns_zone.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_dns_zone
13 short_description: Manage DNS zones on BIG-IP
14 description:
15 - Manage DNS zones on BIG-IP. The zones managed here are primarily used
16 for configuring DNS Express on a BIG-IP. This module does not configure
17 zones that are found in BIG-IP ZoneRunner.
18 version_added: "1.0.0"
19 options:
20 name:
21 description:
22 - Specifies the name of the DNS zone.
23 - The name must begin with a letter and contain only letters, numbers,
24 and the underscore character.
25 type: str
26 required: True
27 dns_express:
28 description:
29 - DNS express related settings.
30 type: dict
31 suboptions:
32 server:
33 description:
34 - Specifies the back-end authoritative DNS server from which the BIG-IP
35 system receives AXFR zone transfers for the DNS Express zone.
36 type: str
37 enabled:
38 description:
39 - Specifies the current status of the DNS Express zone.
40 type: bool
41 notify_action:
42 description:
43 - Specifies the action the system takes when a NOTIFY message is received
44 for this DNS Express zone.
45 - If a TSIG key is configured for the zone, the signature is only validated
46 for C(consume) and C(repeat) actions.
47 - When C(consume), the NOTIFY message is seen only by DNS Express.
48 - When C(bypass), the NOTIFY message does not go to DNS Express, but
49 instead goes to a back-end DNS server (subject to the value of the
50 Unhandled Query Action configured in the DNS profile applied to the
51 listener that handles the DNS request).
52 - When C(repeat), the NOTIFY message goes to both DNS Express and any
53 back-end DNS server.
54 type: str
55 choices:
56 - consume
57 - bypass
58 - repeat
59 allow_notify_from:
60 description:
61 - Specifies the IP addresses from which the system accepts NOTIFY messages
62 for this DNS Express zone.
63 type: list
64 elements: str
65 verify_tsig:
66 description:
67 - Specifies whether the system verifies the identity of the authoritative
68 nameserver that sends updated information for this DNS Express zone.
69 type: bool
70 response_policy:
71 description:
72 - Specifies whether this DNS Express zone is a DNS response policy zone (RPZ).
73 type: bool
74 nameservers:
75 description:
76 - Specifies the DNS nameservers to which the system sends NOTIFY messages.
77 type: list
78 elements: str
79 tsig_server_key:
80 description:
81 - Specifies the TSIG key the system uses to authenticate the back-end DNS
82 authoritative server that sends AXFR zone transfers to the BIG-IP system.
83 type: str
84 state:
85 description:
86 - When C(present), ensures the resource exists.
87 - When C(absent), ensures the resource is removed.
88 type: str
89 choices:
90 - present
91 - absent
92 default: present
93 partition:
94 description:
95 - Device partition to manage resources on.
96 type: str
97 default: Common
98 extends_documentation_fragment: f5networks.f5_modules.f5
99 author:
100 - Tim Rupp (@caphrim007)
101 - Greg Crosby (@crosbygw)
102 '''
103
104 EXAMPLES = r'''
105 - name: Create a DNS zone for DNS express
106 bigip_dns_zone:
107 name: zone.foo.com
108 dns_express:
109 enabled: true
110 server: dns-lab
111 allow_notify_from:
112 - 192.168.39.10
113 notify_action: consume
114 verify_tsig: false
115 response_policy: false
116 provider:
117 password: secret
118 server: lb.mydomain.com
119 user: admin
120 delegate_to: localhost
121
122 - name: Disable DNS express zone, change server, and modify notify_action to bypass
123 bigip_dns_zone:
124 name: zone.foo.com
125 dns_express:
126 enabled: false
127 server: foo1.server.com
128 allow_notify_from:
129 - 192.168.39.10
130 notify_action: bypass
131 verify_tsig: false
132 response_policy: false
133 provider:
134 password: secret
135 server: lb.mydomain.com
136 user: admin
137 delegate_to: localhost
138
139 - name: Add nameservers
140 bigip_dns_zone:
141 name: zone.foo.com
142 nameservers:
143 - foo1.nameserver.com
144 - foo2.nameserver.com
145 - foo3.nameserver.com
146 provider:
147 password: secret
148 server: lb.mydomain.com
149 user: admin
150 delegate_to: localhost
151
152 - name: Remove nameserver
153 bigip_dns_zone:
154 name: zone.foo.com
155 nameservers:
156 - foo1.nameserver.com
157 - foo2.nameserver.com
158 provider:
159 password: secret
160 server: lb.mydomain.com
161 user: admin
162 delegate_to: localhost
163
164 - name: Remove all nameservers
165 bigip_dns_zone:
166 name: zone.foo.com
167 nameservers: none
168 provider:
169 password: secret
170 server: lb.mydomain.com
171 user: admin
172 delegate_to: localhost
173
174 - name: Add tsig_server_key
175 bigip_dns_zone:
176 name: zone.foo.com
177 tsig_server_key: key1
178 provider:
179 password: secret
180 server: lb.mydomain.com
181 user: admin
182 delegate_to: localhost
183
184 - name: Remove tsig_server_key
185 bigip_dns_zone:
186 name: zone.foo.com
187 tsig_server_key: none
188 provider:
189 password: secret
190 server: lb.mydomain.com
191 user: admin
192 delegate_to: localhost
193
194 - name: Remove zone
195 bigip_dns_zone:
196 name: zone.foo.com
197 state: absent
198 provider:
199 password: secret
200 server: lb.mydomain.com
201 user: admin
202 delegate_to: localhost
203 '''
204
205 RETURN = r'''
206 enabled:
207 description: Whether the zone is enabled or not.
208 returned: changed
209 type: bool
210 sample: true
211 allow_notify_from:
212 description: The new DNS Express Allow NOTIFY From value.
213 returned: changed
214 type: list
215 sample: ['1.1.1.1', '2.2.2.2']
216 notify_action:
217 description: The new DNS Express Notify Action value.
218 returned: changed
219 type: str
220 sample: consume
221 verify_tsig:
222 description: The new DNS Express Verify Notify TSIG value.
223 returned: changed
224 type: bool
225 sample: true
226 express_server:
227 description: The new DNS Express Server value.
228 returned: changed
229 type: str
230 sample: server1
231 response_policy:
232 description: The new DNS Express Response Policy value.
233 returned: changed
234 type: bool
235 sample: false
236 nameservers:
237 description: The new Zone Transfer Clients Nameservers value.
238 returned: changed
239 type: list
240 sample: ['/Common/server1', '/Common/server2']
241 tsig_server_key:
242 description: The new TSIG Server Key value.
243 returned: changed
244 type: str
245 sample: /Common/key1
246 '''
247 from datetime import datetime
248
249 from ansible.module_utils.basic import (
250 AnsibleModule, env_fallback
251 )
252
253 from ..module_utils.bigip import F5RestClient
254 from ..module_utils.common import (
255 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
256 )
257 from ..module_utils.compare import cmp_simple_list
258 from ..module_utils.icontrol import tmos_version
259 from ..module_utils.teem import send_teem
260
261
262 class Parameters(AnsibleF5Parameters):
263 api_map = {
264 'dnsExpressEnabled': 'enabled',
265 'dnsExpressAllowNotify': 'allow_notify_from',
266 'dnsExpressNotifyAction': 'notify_action',
267 'dnsExpressNotifyTsigVerify': 'verify_tsig',
268 'dnsExpressServer': 'express_server',
269 'responsePolicy': 'response_policy',
270 'transferClients': 'nameservers',
271 'serverTsigKey': 'tsig_server_key',
272 }
273
274 api_attributes = [
275 'dnsExpressEnabled',
276 'dnsExpressAllowNotify',
277 'dnsExpressNotifyAction',
278 'dnsExpressNotifyTsigVerify',
279 'dnsExpressServer',
280 'responsePolicy',
281 'transferClients',
282 'serverTsigKey',
283 ]
284
285 returnables = [
286 'enabled',
287 'allow_notify_from',
288 'notify_action',
289 'verify_tsig',
290 'express_server',
291 'response_policy',
292 'nameservers',
293 'tsig_server_key',
294 ]
295
296 updatables = [
297 'enabled',
298 'allow_notify_from',
299 'notify_action',
300 'verify_tsig',
301 'express_server',
302 'response_policy',
303 'nameservers',
304 'tsig_server_key',
305 ]
306
307
308 class ApiParameters(Parameters):
309 pass
310
311
312 class ModuleParameters(Parameters):
313 @property
314 def express_server(self):
315 try:
316 if self._values['dns_express']['server'] is None:
317 return None
318 if self._values['dns_express']['server'] in ['', 'none']:
319 return ''
320 return fq_name(self.partition, self._values['dns_express']['server'])
321 except (TypeError, KeyError):
322 return None
323
324 @property
325 def nameservers(self):
326 if self._values['nameservers'] is None:
327 return None
328 elif len(self._values['nameservers']) == 1 and self._values['nameservers'][0] in ['', 'none']:
329 return ''
330 return [fq_name(self.partition, x) for x in self._values['nameservers']]
331
332 @property
333 def tsig_server_key(self):
334 if self._values['tsig_server_key'] is None:
335 return None
336 if self._values['tsig_server_key'] in ['', 'none']:
337 return ''
338 return fq_name(self.partition, self._values['tsig_server_key'])
339
340 @property
341 def enabled(self):
342 try:
343 return flatten_boolean(self._values['dns_express']['enabled'])
344 except (TypeError, KeyError):
345 return None
346
347 @property
348 def verify_tsig(self):
349 try:
350 return flatten_boolean(self._values['dns_express']['verify_tsig'])
351 except (TypeError, KeyError):
352 return None
353
354 @property
355 def notify_action(self):
356 try:
357 return self._values['dns_express']['notify_action']
358 except (TypeError, KeyError):
359 return None
360
361 @property
362 def response_policy(self):
363 try:
364 return flatten_boolean(self._values['dns_express']['response_policy'])
365 except (TypeError, KeyError):
366 return None
367
368 @property
369 def allow_notify_from(self):
370 try:
371 v = self._values['dns_express']['allow_notify_from']
372 if v is None:
373 return None
374 elif len(v) == 1 and v[0] in ['', 'none']:
375 return ''
376 return v
377 except (TypeError, KeyError):
378 return None
379
380
381 class Changes(Parameters):
382 def to_return(self):
383 result = {}
384 try:
385 for returnable in self.returnables:
386 result[returnable] = getattr(self, returnable)
387 result = self._filter_params(result)
388 except Exception:
389 raise
390 return result
391
392
393 class UsableChanges(Changes):
394 pass
395
396
397 class ReportableChanges(Changes):
398 pass
399
400
401 class Difference(object):
402 def __init__(self, want, have=None):
403 self.want = want
404 self.have = have
405
406 def compare(self, param):
407 try:
408 result = getattr(self, param)
409 return result
410 except AttributeError:
411 return self.__default(param)
412
413 @property
414 def allow_notify_from(self):
415 return cmp_simple_list(self.want.allow_notify_from, self.have.allow_notify_from)
416
417 @property
418 def nameservers(self):
419 return cmp_simple_list(self.want.nameservers, self.have.nameservers)
420
421 @property
422 def express_server(self):
423 if self.want.express_server is None:
424 return None
425 if self.want.express_server == '' and self.have.express_server is None:
426 return None
427 if self.want.express_server != self.have.express_server:
428 return self.want.express_server
429
430 @property
431 def tsig_server_key(self):
432 if self.want.tsig_server_key is None:
433 return None
434 if self.want.tsig_server_key == '' and self.have.tsig_server_key is None:
435 return None
436 if self.want.tsig_server_key != self.have.tsig_server_key:
437 return self.want.tsig_server_key
438
439 def __default(self, param):
440 attr1 = getattr(self.want, param)
441 try:
442 attr2 = getattr(self.have, param)
443 if attr1 != attr2:
444 return attr1
445 except AttributeError:
446 return attr1
447
448
449 class ModuleManager(object):
450 def __init__(self, *args, **kwargs):
451 self.module = kwargs.get('module', None)
452 self.client = F5RestClient(**self.module.params)
453 self.want = ModuleParameters(params=self.module.params)
454 self.have = ApiParameters()
455 self.changes = UsableChanges()
456
457 def _set_changed_options(self):
458 changed = {}
459 for key in Parameters.returnables:
460 if getattr(self.want, key) is not None:
461 changed[key] = getattr(self.want, key)
462 if changed:
463 self.changes = UsableChanges(params=changed)
464
465 def _update_changed_options(self):
466 diff = Difference(self.want, self.have)
467 updatables = Parameters.updatables
468 changed = dict()
469 for k in updatables:
470 change = diff.compare(k)
471 if change is None:
472 continue
473 else:
474 if isinstance(change, dict):
475 changed.update(change)
476 else:
477 changed[k] = change
478 if changed:
479 self.changes = UsableChanges(params=changed)
480 return True
481 return False
482
483 def should_update(self):
484 result = self._update_changed_options()
485 if result:
486 return True
487 return False
488
489 def exec_module(self):
490 start = datetime.now().isoformat()
491 version = tmos_version(self.client)
492 changed = False
493 result = dict()
494 state = self.want.state
495
496 if state == "present":
497 changed = self.present()
498 elif state == "absent":
499 changed = self.absent()
500
501 reportable = ReportableChanges(params=self.changes.to_return())
502 changes = reportable.to_return()
503 result.update(**changes)
504 result.update(dict(changed=changed))
505 self._announce_deprecations(result)
506 send_teem(start, self.client, self.module, version)
507 return result
508
509 def _announce_deprecations(self, result):
510 warnings = result.pop('__warnings', [])
511 for warning in warnings:
512 self.client.module.deprecate(
513 msg=warning['msg'],
514 version=warning['version']
515 )
516
517 def present(self):
518 if self.exists():
519 return self.update()
520 else:
521 return self.create()
522
523 def exists(self):
524 errors = [401, 403, 409, 500, 501, 502, 503, 504]
525 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
526 self.client.provider['server'],
527 self.client.provider['server_port'],
528 transform_name(self.want.partition, self.want.name)
529 )
530 resp = self.client.api.get(uri)
531 try:
532 response = resp.json()
533 except ValueError as ex:
534 raise F5ModuleError(str(ex))
535
536 if resp.status == 404 or 'code' in response and response['code'] == 404:
537 return False
538 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
539 return True
540
541 if resp.status in errors or 'code' in response and response['code'] in errors:
542 if 'message' in response:
543 raise F5ModuleError(response['message'])
544 else:
545 raise F5ModuleError(resp.content)
546
547 def update(self):
548 self.have = self.read_current_from_device()
549 if not self.should_update():
550 return False
551 if self.module.check_mode:
552 return True
553 self.update_on_device()
554 return True
555
556 def remove(self):
557 if self.module.check_mode:
558 return True
559 self.remove_from_device()
560 if self.exists():
561 raise F5ModuleError("Failed to delete the resource.")
562 return True
563
564 def create(self):
565 self._set_changed_options()
566 if self.module.check_mode:
567 return True
568 self.create_on_device()
569 return True
570
571 def create_on_device(self):
572 params = self.changes.api_params()
573 params['name'] = self.want.name
574 params['partition'] = self.want.partition
575 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/".format(
576 self.client.provider['server'],
577 self.client.provider['server_port']
578 )
579 resp = self.client.api.post(uri, json=params)
580 try:
581 response = resp.json()
582 except ValueError as ex:
583 raise F5ModuleError(str(ex))
584
585 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
586 return True
587 raise F5ModuleError(resp.content)
588
589 def update_on_device(self):
590 params = self.changes.api_params()
591 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
592 self.client.provider['server'],
593 self.client.provider['server_port'],
594 transform_name(self.want.partition, self.want.name)
595 )
596 resp = self.client.api.patch(uri, json=params)
597 try:
598 response = resp.json()
599 except ValueError as ex:
600 raise F5ModuleError(str(ex))
601
602 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
603 return True
604 raise F5ModuleError(resp.content)
605
606 def absent(self):
607 if self.exists():
608 return self.remove()
609 return False
610
611 def remove_from_device(self):
612 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
613 self.client.provider['server'],
614 self.client.provider['server_port'],
615 transform_name(self.want.partition, self.want.name)
616 )
617 response = self.client.api.delete(uri)
618 if response.status == 200:
619 return True
620 raise F5ModuleError(response.content)
621
622 def read_current_from_device(self):
623 uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
624 self.client.provider['server'],
625 self.client.provider['server_port'],
626 transform_name(self.want.partition, self.want.name)
627 )
628 resp = self.client.api.get(uri)
629 try:
630 response = resp.json()
631 except ValueError as ex:
632 raise F5ModuleError(str(ex))
633
634 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
635 return ApiParameters(params=response)
636 raise F5ModuleError(resp.content)
637
638
639 class ArgumentSpec(object):
640 def __init__(self):
641 self.supports_check_mode = True
642 argument_spec = dict(
643 name=dict(required=True),
644 dns_express=dict(
645 type='dict',
646 options=dict(
647 server=dict(),
648 enabled=dict(type='bool'),
649 notify_action=dict(
650 choices=['consume', 'bypass', 'repeat']
651 ),
652 allow_notify_from=dict(
653 type='list',
654 elements='str',
655 ),
656 verify_tsig=dict(type='bool'),
657 response_policy=dict(type='bool')
658 )
659 ),
660 nameservers=dict(
661 type='list',
662 elements='str',
663 ),
664 tsig_server_key=dict(no_log=True),
665 partition=dict(
666 default='Common',
667 fallback=(env_fallback, ['F5_PARTITION'])
668 ),
669 state=dict(
670 default='present',
671 choices=['present', 'absent']
672 )
673 )
674 self.argument_spec = {}
675 self.argument_spec.update(f5_argument_spec)
676 self.argument_spec.update(argument_spec)
677
678
679 def main():
680 spec = ArgumentSpec()
681
682 module = AnsibleModule(
683 argument_spec=spec.argument_spec,
684 supports_check_mode=spec.supports_check_mode,
685 )
686
687 try:
688 mm = ModuleManager(module=module)
689 results = mm.exec_module()
690 module.exit_json(**results)
691 except F5ModuleError as ex:
692 module.fail_json(msg=str(ex))
693
694
695 if __name__ == '__main__':
696 main()