Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, 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_profile_dns
13 short_description: Manage DNS profiles on a BIG-IP
14 description:
15 - Manage DNS profiles on a BIG-IP. There are many DNS profiles options, each with their
16 own adjustments to the standard C(dns) profile. Users of this module should be aware
17 that many of the configurable options have no module default. Instead, the default is
18 assigned by the BIG-IP system itself which, in most cases, is acceptable.
19 version_added: "1.0.0"
20 options:
21 name:
22 description:
23 - Specifies the name of the DNS profile.
24 type: str
25 required: True
26 parent:
27 description:
28 - Specifies the profile from which this profile inherits settings.
29 - When creating a new profile, if this parameter is not specified, the default
30 is the system-supplied C(dns) profile.
31 type: str
32 enable_dns_express:
33 description:
34 - Specifies whether the DNS Express engine is enabled.
35 - When creating a new profile, if this parameter is not specified, the default
36 is provided by the parent profile.
37 - The DNS Express engine receives zone transfers from the authoritative DNS server
38 for the zone. If the C(enable_zone_transfer) setting is also C(true) on this profile,
39 the DNS Express engine also responds to zone transfer requests made by the nameservers
40 configured as zone transfer clients for the DNS Express zone.
41 type: bool
42 enable_zone_transfer:
43 description:
44 - Specifies whether the system answers zone transfer requests for a DNS zone created
45 on the system.
46 - When creating a new profile, if this parameter is not specified, the default
47 is provided by the parent profile.
48 - The C(enable_dns_express) and C(enable_zone_transfer) settings on a DNS profile
49 affect how the system responds to zone transfer requests.
50 - When the C(enable_dns_express) and C(enable_zone_transfer) settings are both C(true),
51 if a zone transfer request matches a DNS Express zone, DNS Express answers the
52 request.
53 - When the C(enable_dns_express) setting is C(no) and the C(enable_zone_transfer)
54 setting is C(true), the BIG-IP system processes zone transfer requests based on the
55 last action and answers the request from local BIND or a pool member.
56 type: bool
57 enable_dnssec:
58 description:
59 - Specifies whether the system signs responses with DNSSEC keys and replies to DNSSEC
60 specific queries (for example, DNSKEY query type).
61 - When creating a new profile, if this parameter is not specified, the default
62 is provided by the parent profile.
63 type: bool
64 enable_gtm:
65 description:
66 - Specifies whether the system uses Global Traffic Manager (now BIG-IP DNS) to manage the response.
67 - When creating a new profile, if this parameter is not specified, the default
68 is provided by the parent profile.
69 type: bool
70 process_recursion_desired:
71 description:
72 - Specifies whether to process client-side DNS packets with Recursion Desired set in
73 the header.
74 - When creating a new profile, if this parameter is not specified, the default
75 is provided by the parent profile.
76 - If set to C(false), processing of the packet is subject to the unhandled-query-action
77 option.
78 type: bool
79 use_local_bind:
80 description:
81 - Specifies whether the system forwards non-wide IP queries to the local BIND server
82 on the BIG-IP system.
83 - For best performance, disable this setting when using a DNS cache.
84 - When creating a new profile, if this parameter is not specified, the default
85 is provided by the parent profile.
86 type: bool
87 enable_dns_firewall:
88 description:
89 - Specifies whether the DNS firewall is enabled.
90 - When creating a new profile, if this parameter is not specified, the default
91 is provided by the parent profile.
92 type: bool
93 enable_cache:
94 description:
95 - Specifies whether the system caches DNS responses.
96 - When creating a new profile, if this parameter is not specified, the default
97 is provided by the parent profile.
98 - When C(true), the BIG-IP system caches DNS responses handled by the virtual
99 servers associated with this profile. When you enable this setting, you must
100 also specify a value for C(cache_name).
101 - When C(false), the BIG-IP system does not cache DNS responses handled by the
102 virtual servers associated with this profile. However, the profile retains
103 the association with the DNS cache in the C(cache_name) parameter. Disable
104 this setting when you want to debug the system.
105 type: bool
106 cache_name:
107 description:
108 - Specifies the user-created cache the system uses to cache DNS responses.
109 - When you select a cache for the system to use, you must also set C(enable_dns_cache)
110 to C(true)
111 type: str
112 unhandled_query_action:
113 description:
114 - Specifies the action to take when a query does not match a Wide IP or a DNS Express Zone.
115 - When C(allow), the BIG-IP system forwards queries to a DNS server or pool member.
116 If a pool is not associated with a listener and the Use BIND Server on BIG-IP setting
117 is set to Enabled, requests are forwarded to the local BIND server.
118 - When C(drop), the BIG-IP system does not respond to the query.
119 - When C(reject), the BIG-IP system returns the query with the REFUSED return code.
120 - When C(hint), the BIG-IP system returns the query with a list of root name servers.
121 - When C(no-error), the BIG-IP system returns the query with the NOERROR return code.
122 - When creating a new profile, if this parameter is not specified, the default
123 is provided by the parent profile.
124 type: str
125 choices:
126 - allow
127 - drop
128 - reject
129 - hint
130 - no-error
131 partition:
132 description:
133 - Device partition to manage resources on.
134 type: str
135 default: Common
136 state:
137 description:
138 - When C(present), ensures the profile exists.
139 - When C(absent), ensures the profile is removed.
140 type: str
141 choices:
142 - present
143 - absent
144 default: present
145 extends_documentation_fragment: f5networks.f5_modules.f5
146 author:
147 - Tim Rupp (@caphrim007)
148 '''
149
150 EXAMPLES = r'''
151 - name: Create a DNS profile
152 bigip_profile_dns:
153 name: foo
154 enable_dns_express: false
155 enable_dnssec: false
156 enable_gtm: false
157 process_recursion_desired: false
158 use_local_bind: false
159 enable_dns_firewall: true
160 provider:
161 password: secret
162 server: lb.mydomain.com
163 user: admin
164 delegate_to: localhost
165 '''
166
167 RETURN = r'''
168 enable_dns_express:
169 description: Whether DNS Express is enabled on the resource or not.
170 returned: changed
171 type: bool
172 sample: true
173 enable_zone_transfer:
174 description: Whether zone transfer are enabled on the resource or not.
175 returned: changed
176 type: bool
177 sample: false
178 enable_dnssec:
179 description: Whether DNSSEC is enabled on the resource or not.
180 returned: changed
181 type: bool
182 sample: false
183 enable_gtm:
184 description: Whether GTM is used to manage the resource or not.
185 returned: changed
186 type: bool
187 sample: true
188 process_recursion_desired:
189 description: Whether client-side DNS packets are processed with Recursion Desired set.
190 returned: changed
191 type: bool
192 sample: true
193 use_local_bind:
194 description: Whether non-wide IP queries are forwarded to the local BIND server or not.
195 returned: changed
196 type: bool
197 sample: false
198 enable_dns_firewall:
199 description: Whether DNS firewall capability is enabled or not.
200 returned: changed
201 type: bool
202 sample: false
203 enable_cache:
204 description: Whether DNS caching is enabled or not.
205 returned: changed
206 type: bool
207 sample: false
208 cache_name:
209 description: Name of the cache used by DNS.
210 returned: changed
211 type: str
212 sample: /Common/cache1
213 unhandled_query_action:
214 description: What to do with unhandled queries
215 returned: changed
216 type: str
217 sample: allow
218 '''
219 from datetime import datetime
220 from ansible.module_utils.basic import (
221 AnsibleModule, env_fallback
222 )
223
224 from ..module_utils.bigip import F5RestClient
225 from ..module_utils.common import (
226 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
227 )
228 from ..module_utils.icontrol import tmos_version
229 from ..module_utils.teem import send_teem
230
231
232 class Parameters(AnsibleF5Parameters):
233 api_map = {
234 'enableDnsFirewall': 'enable_dns_firewall',
235 'useLocalBind': 'use_local_bind',
236 'processRd': 'process_recursion_desired',
237 'enableGtm': 'enable_gtm',
238 'enableDnssec': 'enable_dnssec',
239 'processXfr': 'enable_zone_transfer',
240 'enableDnsExpress': 'enable_dns_express',
241 'defaultsFrom': 'parent',
242 'enableCache': 'enable_cache',
243 'cache': 'cache_name',
244 'unhandledQueryAction': 'unhandled_query_action',
245 }
246
247 api_attributes = [
248 'enableDnsFirewall',
249 'useLocalBind',
250 'processRd',
251 'enableGtm',
252 'enableDnssec',
253 'processXfr',
254 'enableDnsExpress',
255 'defaultsFrom',
256 'cache',
257 'enableCache',
258 'unhandledQueryAction',
259 ]
260
261 returnables = [
262 'enable_dns_firewall',
263 'use_local_bind',
264 'process_recursion_desired',
265 'enable_gtm',
266 'enable_dnssec',
267 'enable_zone_transfer',
268 'enable_dns_express',
269 'cache_name',
270 'enable_cache',
271 'unhandled_query_action',
272 ]
273
274 updatables = [
275 'enable_dns_firewall',
276 'use_local_bind',
277 'process_recursion_desired',
278 'enable_gtm',
279 'enable_dnssec',
280 'enable_zone_transfer',
281 'enable_dns_express',
282 'cache_name',
283 'enable_cache',
284 'unhandled_query_action',
285 ]
286
287
288 class ApiParameters(Parameters):
289 @property
290 def enable_dns_firewall(self):
291 if self._values['enable_dns_firewall'] is None:
292 return None
293 if self._values['enable_dns_firewall'] == 'yes':
294 return True
295 return False
296
297 @property
298 def use_local_bind(self):
299 if self._values['use_local_bind'] is None:
300 return None
301 if self._values['use_local_bind'] == 'yes':
302 return True
303 return False
304
305 @property
306 def process_recursion_desired(self):
307 if self._values['process_recursion_desired'] is None:
308 return None
309 if self._values['process_recursion_desired'] == 'yes':
310 return True
311 return False
312
313 @property
314 def enable_gtm(self):
315 if self._values['enable_gtm'] is None:
316 return None
317 if self._values['enable_gtm'] == 'yes':
318 return True
319 return False
320
321 @property
322 def enable_cache(self):
323 if self._values['enable_cache'] is None:
324 return None
325 if self._values['enable_cache'] == 'yes':
326 return True
327 return False
328
329 @property
330 def enable_dnssec(self):
331 if self._values['enable_dnssec'] is None:
332 return None
333 if self._values['enable_dnssec'] == 'yes':
334 return True
335 return False
336
337 @property
338 def enable_zone_transfer(self):
339 if self._values['enable_zone_transfer'] is None:
340 return None
341 if self._values['enable_zone_transfer'] == 'yes':
342 return True
343 return False
344
345 @property
346 def enable_dns_express(self):
347 if self._values['enable_dns_express'] is None:
348 return None
349 if self._values['enable_dns_express'] == 'yes':
350 return True
351 return False
352
353 @property
354 def unhandled_query_action(self):
355 if self._values['unhandled_query_action'] is None:
356 return None
357 elif self._values['unhandled_query_action'] == 'noerror':
358 return 'no-error'
359 return self._values['unhandled_query_action']
360
361
362 class ModuleParameters(Parameters):
363 @property
364 def parent(self):
365 if self._values['parent'] is None:
366 return None
367 result = fq_name(self.partition, self._values['parent'])
368 return result
369
370 @property
371 def cache_name(self):
372 if self._values['cache_name'] is None:
373 return None
374 if self._values['cache_name'] == '':
375 return ''
376 result = fq_name(self.partition, self._values['cache_name'])
377 return result
378
379
380 class Changes(Parameters):
381 def to_return(self):
382 result = {}
383 try:
384 for returnable in self.returnables:
385 result[returnable] = getattr(self, returnable)
386 result = self._filter_params(result)
387 except Exception:
388 pass
389 return result
390
391
392 class UsableChanges(Changes):
393 @property
394 def enable_dns_firewall(self):
395 if self._values['enable_dns_firewall'] is None:
396 return None
397 if self._values['enable_dns_firewall']:
398 return 'yes'
399 return 'no'
400
401 @property
402 def use_local_bind(self):
403 if self._values['use_local_bind'] is None:
404 return None
405 if self._values['use_local_bind']:
406 return 'yes'
407 return 'no'
408
409 @property
410 def process_recursion_desired(self):
411 if self._values['process_recursion_desired'] is None:
412 return None
413 if self._values['process_recursion_desired']:
414 return 'yes'
415 return 'no'
416
417 @property
418 def enable_gtm(self):
419 if self._values['enable_gtm'] is None:
420 return None
421 if self._values['enable_gtm']:
422 return 'yes'
423 return 'no'
424
425 @property
426 def enable_cache(self):
427 if self._values['enable_cache'] is None:
428 return None
429 if self._values['enable_cache']:
430 return 'yes'
431 return 'no'
432
433 @property
434 def enable_dnssec(self):
435 if self._values['enable_dnssec'] is None:
436 return None
437 if self._values['enable_dnssec']:
438 return 'yes'
439 return 'no'
440
441 @property
442 def enable_zone_transfer(self):
443 if self._values['enable_zone_transfer'] is None:
444 return None
445 if self._values['enable_zone_transfer']:
446 return 'yes'
447 return 'no'
448
449 @property
450 def enable_dns_express(self):
451 if self._values['enable_dns_express'] is None:
452 return None
453 if self._values['enable_dns_express']:
454 return 'yes'
455 return 'no'
456
457 @property
458 def unhandled_query_action(self):
459 if self._values['unhandled_query_action'] is None:
460 return None
461 elif self._values['unhandled_query_action'] == 'no-error':
462 return 'noerror'
463 return self._values['unhandled_query_action']
464
465
466 class ReportableChanges(Changes):
467 pass
468
469
470 class Difference(object):
471 def __init__(self, want, have=None):
472 self.want = want
473 self.have = have
474
475 def compare(self, param):
476 try:
477 result = getattr(self, param)
478 return result
479 except AttributeError:
480 return self.__default(param)
481
482 def __default(self, param):
483 attr1 = getattr(self.want, param)
484 try:
485 attr2 = getattr(self.have, param)
486 if attr1 != attr2:
487 return attr1
488 except AttributeError:
489 return attr1
490
491
492 class ModuleManager(object):
493 def __init__(self, *args, **kwargs):
494 self.module = kwargs.get('module', None)
495 self.client = F5RestClient(**self.module.params)
496 self.want = ModuleParameters(params=self.module.params)
497 self.have = ApiParameters()
498 self.changes = UsableChanges()
499
500 def _set_changed_options(self):
501 changed = {}
502 for key in Parameters.returnables:
503 if getattr(self.want, key) is not None:
504 changed[key] = getattr(self.want, key)
505 if changed:
506 self.changes = UsableChanges(params=changed)
507
508 def _update_changed_options(self):
509 diff = Difference(self.want, self.have)
510 updatables = Parameters.updatables
511 changed = dict()
512 for k in updatables:
513 change = diff.compare(k)
514 if change is None:
515 continue
516 else:
517 if isinstance(change, dict):
518 changed.update(change)
519 else:
520 changed[k] = change
521 if changed:
522 self.changes = UsableChanges(params=changed)
523 return True
524 return False
525
526 def should_update(self):
527 result = self._update_changed_options()
528 if result:
529 return True
530 return False
531
532 def exec_module(self):
533 start = datetime.now().isoformat()
534 version = tmos_version(self.client)
535 changed = False
536 result = dict()
537 state = self.want.state
538
539 if state == "present":
540 changed = self.present()
541 elif state == "absent":
542 changed = self.absent()
543
544 reportable = ReportableChanges(params=self.changes.to_return())
545 changes = reportable.to_return()
546 result.update(**changes)
547 result.update(dict(changed=changed))
548 self._announce_deprecations(result)
549 send_teem(start, self.client, self.module, version)
550 return result
551
552 def _announce_deprecations(self, result):
553 warnings = result.pop('__warnings', [])
554 for warning in warnings:
555 self.client.module.deprecate(
556 msg=warning['msg'],
557 version=warning['version']
558 )
559
560 def present(self):
561 if self.exists():
562 return self.update()
563 else:
564 return self.create()
565
566 def exists(self):
567 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dns/{2}".format(
568 self.client.provider['server'],
569 self.client.provider['server_port'],
570 transform_name(self.want.partition, self.want.name)
571 )
572 resp = self.client.api.get(uri)
573 try:
574 response = resp.json()
575 except ValueError as ex:
576 raise F5ModuleError(str(ex))
577
578 if resp.status == 404 or 'code' in response and response['code'] == 404:
579 return False
580 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
581 return True
582
583 errors = [401, 403, 409, 500, 501, 502, 503, 504]
584
585 if resp.status in errors or 'code' in response and response['code'] in errors:
586 if 'message' in response:
587 raise F5ModuleError(response['message'])
588 else:
589 raise F5ModuleError(resp.content)
590
591 def update(self):
592 self.have = self.read_current_from_device()
593 if not self.should_update():
594 return False
595 if self.changes.enable_cache is True or self.have.enable_cache is True:
596 if not self.have.cache_name or self.changes.cache_name == '':
597 raise F5ModuleError(
598 "To enable DNS cache, a DNS cache must be specified."
599 )
600 if self.module.check_mode:
601 return True
602 self.update_on_device()
603 return True
604
605 def remove(self):
606 if self.module.check_mode:
607 return True
608 self.remove_from_device()
609 if self.exists():
610 raise F5ModuleError("Failed to delete the resource.")
611 return True
612
613 def create(self):
614 self._set_changed_options()
615 if self.want.enable_cache is True and not self.want.cache_name:
616 raise F5ModuleError(
617 "You must specify a 'cache_name' when creating a DNS profile that sets 'enable_cache' to 'yes'."
618 )
619
620 if self.module.check_mode:
621 return True
622 self.create_on_device()
623 return True
624
625 def create_on_device(self):
626 params = self.changes.api_params()
627 params['name'] = self.want.name
628 params['partition'] = self.want.partition
629 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dns/".format(
630 self.client.provider['server'],
631 self.client.provider['server_port']
632 )
633 resp = self.client.api.post(uri, json=params)
634 try:
635 response = resp.json()
636 except ValueError as ex:
637 raise F5ModuleError(str(ex))
638
639 if 'code' in response and response['code'] in [400, 403, 404]:
640 if 'message' in response:
641 raise F5ModuleError(response['message'])
642 else:
643 raise F5ModuleError(resp.content)
644
645 def update_on_device(self):
646 params = self.changes.api_params()
647 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dns/{2}".format(
648 self.client.provider['server'],
649 self.client.provider['server_port'],
650 transform_name(self.want.partition, self.want.name)
651 )
652 resp = self.client.api.patch(uri, json=params)
653 try:
654 response = resp.json()
655 except ValueError as ex:
656 raise F5ModuleError(str(ex))
657
658 if 'code' in response and response['code'] in [400, 404]:
659 if 'message' in response:
660 raise F5ModuleError(response['message'])
661 else:
662 raise F5ModuleError(resp.content)
663
664 def absent(self):
665 if self.exists():
666 return self.remove()
667 return False
668
669 def remove_from_device(self):
670 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dns/{2}".format(
671 self.client.provider['server'],
672 self.client.provider['server_port'],
673 transform_name(self.want.partition, self.want.name)
674 )
675 response = self.client.api.delete(uri)
676 if response.status == 200:
677 return True
678 raise F5ModuleError(response.content)
679
680 def read_current_from_device(self):
681 uri = "https://{0}:{1}/mgmt/tm/ltm/profile/dns/{2}".format(
682 self.client.provider['server'],
683 self.client.provider['server_port'],
684 transform_name(self.want.partition, self.want.name)
685 )
686 resp = self.client.api.get(uri)
687 try:
688 response = resp.json()
689 except ValueError as ex:
690 raise F5ModuleError(str(ex))
691
692 if 'code' in response and response['code'] == 400:
693 if 'message' in response:
694 raise F5ModuleError(response['message'])
695 else:
696 raise F5ModuleError(resp.content)
697 return ApiParameters(params=response)
698
699
700 class ArgumentSpec(object):
701 def __init__(self):
702 self.supports_check_mode = True
703 argument_spec = dict(
704 name=dict(required=True),
705 parent=dict(),
706 enable_dns_express=dict(type='bool'),
707 enable_zone_transfer=dict(type='bool'),
708 enable_dnssec=dict(type='bool'),
709 enable_gtm=dict(type='bool'),
710 process_recursion_desired=dict(type='bool'),
711 use_local_bind=dict(type='bool'),
712 enable_dns_firewall=dict(type='bool'),
713 enable_cache=dict(type='bool'),
714 unhandled_query_action=dict(
715 choices=['allow', 'drop', 'reject', 'hint', 'no-error']
716 ),
717 cache_name=dict(),
718 state=dict(
719 default='present',
720 choices=['present', 'absent']
721 ),
722 partition=dict(
723 default='Common',
724 fallback=(env_fallback, ['F5_PARTITION'])
725 )
726 )
727 self.argument_spec = {}
728 self.argument_spec.update(f5_argument_spec)
729 self.argument_spec.update(argument_spec)
730
731
732 def main():
733 spec = ArgumentSpec()
734
735 module = AnsibleModule(
736 argument_spec=spec.argument_spec,
737 supports_check_mode=spec.supports_check_mode
738 )
739
740 try:
741 mm = ModuleManager(module=module)
742 results = mm.exec_module()
743 module.exit_json(**results)
744 except F5ModuleError as ex:
745 module.fail_json(msg=str(ex))
746
747
748 if __name__ == '__main__':
749 main()