Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_dns.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_system_dns
23 short_description: Configure DNS in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify system feature and dns category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 system_dns:
80 description:
81 - Configure DNS.
82 default: null
83 type: dict
84 suboptions:
85 alt_primary:
86 description:
87 - Alternate primary DNS server. This is not used as a failover DNS server.
88 type: str
89 alt_secondary:
90 description:
91 - Alternate secondary DNS server. This is not used as a failover DNS server.
92 type: str
93 cache_notfound_responses:
94 description:
95 - Enable/disable response from the DNS server when a record is not in cache.
96 type: str
97 choices:
98 - 'disable'
99 - 'enable'
100 dns_cache_limit:
101 description:
102 - Maximum number of records in the DNS cache.
103 type: int
104 dns_cache_ttl:
105 description:
106 - Duration in seconds that the DNS cache retains information.
107 type: int
108 dns_over_tls:
109 description:
110 - Enable/disable/enforce DNS over TLS.
111 type: str
112 choices:
113 - 'disable'
114 - 'enable'
115 - 'enforce'
116 domain:
117 description:
118 - Search suffix list for hostname lookup.
119 type: list
120 elements: dict
121 suboptions:
122 domain:
123 description:
124 - DNS search domain list separated by space (maximum 8 domains).
125 required: true
126 type: str
127 fqdn_cache_ttl:
128 description:
129 - FQDN cache time to live in seconds (0 - 86400).
130 type: int
131 fqdn_max_refresh:
132 description:
133 - FQDN cache maximum refresh time in seconds (3600 - 86400).
134 type: int
135 fqdn_min_refresh:
136 description:
137 - FQDN cache minimum refresh time in seconds (10 - 3600).
138 type: int
139 hostname_limit:
140 description:
141 - Limit of the number of hostname table entries (0 - 50000).
142 type: int
143 hostname_ttl:
144 description:
145 - TTL of hostname table entries (60 - 86400).
146 type: int
147 interface:
148 description:
149 - Specify outgoing interface to reach server. Source system.interface.name.
150 type: str
151 interface_select_method:
152 description:
153 - Specify how to select outgoing interface to reach server.
154 type: str
155 choices:
156 - 'auto'
157 - 'sdwan'
158 - 'specify'
159 ip6_primary:
160 description:
161 - Primary DNS server IPv6 address.
162 type: str
163 ip6_secondary:
164 description:
165 - Secondary DNS server IPv6 address.
166 type: str
167 log:
168 description:
169 - Local DNS log setting.
170 type: str
171 choices:
172 - 'disable'
173 - 'error'
174 - 'all'
175 primary:
176 description:
177 - Primary DNS server IP address.
178 type: str
179 protocol:
180 description:
181 - DNS transport protocols.
182 type: list
183 elements: str
184 choices:
185 - 'cleartext'
186 - 'dot'
187 - 'doh'
188 retry:
189 description:
190 - Number of times to retry (0 - 5).
191 type: int
192 root_servers:
193 description:
194 - Configure up to two preferred servers that serve the DNS root zone .
195 type: list
196 elements: str
197 secondary:
198 description:
199 - Secondary DNS server IP address.
200 type: str
201 server_hostname:
202 description:
203 - DNS server host name list.
204 type: list
205 elements: dict
206 suboptions:
207 hostname:
208 description:
209 - DNS server host name list separated by space (maximum 4 domains).
210 required: true
211 type: str
212 server_select_method:
213 description:
214 - Specify how configured servers are prioritized.
215 type: str
216 choices:
217 - 'least-rtt'
218 - 'failover'
219 source_ip:
220 description:
221 - IP address used by the DNS server as its source IP.
222 type: str
223 source_ip_interface:
224 description:
225 - IP address of the specified interface as the source IP address. Source system.interface.name.
226 type: str
227 ssl_certificate:
228 description:
229 - Name of local certificate for SSL connections. Source certificate.local.name.
230 type: str
231 timeout:
232 description:
233 - DNS query timeout interval in seconds (1 - 10).
234 type: int
235 vrf_select:
236 description:
237 - VRF ID used for connection to server.
238 type: int
239 """
240
241 EXAMPLES = """
242 - name: Configure DNS.
243 fortinet.fortios.fortios_system_dns:
244 vdom: "{{ vdom }}"
245 system_dns:
246 alt_primary: "<your_own_value>"
247 alt_secondary: "<your_own_value>"
248 cache_notfound_responses: "disable"
249 dns_cache_limit: "5000"
250 dns_cache_ttl: "1800"
251 dns_over_tls: "disable"
252 domain:
253 -
254 domain: "<your_own_value>"
255 fqdn_cache_ttl: "0"
256 fqdn_max_refresh: "3600"
257 fqdn_min_refresh: "60"
258 hostname_limit: "5000"
259 hostname_ttl: "86400"
260 interface: "<your_own_value> (source system.interface.name)"
261 interface_select_method: "auto"
262 ip6_primary: "<your_own_value>"
263 ip6_secondary: "<your_own_value>"
264 log: "disable"
265 primary: "<your_own_value>"
266 protocol: "cleartext"
267 retry: "2"
268 root_servers: "<your_own_value>"
269 secondary: "<your_own_value>"
270 server_hostname:
271 -
272 hostname: "myhostname"
273 server_select_method: "least-rtt"
274 source_ip: "84.230.14.43"
275 source_ip_interface: "<your_own_value> (source system.interface.name)"
276 ssl_certificate: "<your_own_value> (source certificate.local.name)"
277 timeout: "5"
278 vrf_select: "0"
279 """
280
281 RETURN = """
282 build:
283 description: Build number of the fortigate image
284 returned: always
285 type: str
286 sample: '1547'
287 http_method:
288 description: Last method used to provision the content into FortiGate
289 returned: always
290 type: str
291 sample: 'PUT'
292 http_status:
293 description: Last result given by FortiGate on last operation applied
294 returned: always
295 type: str
296 sample: "200"
297 mkey:
298 description: Master key (id) used in the last call to FortiGate
299 returned: success
300 type: str
301 sample: "id"
302 name:
303 description: Name of the table used to fulfill the request
304 returned: always
305 type: str
306 sample: "urlfilter"
307 path:
308 description: Path of the table used to fulfill the request
309 returned: always
310 type: str
311 sample: "webfilter"
312 revision:
313 description: Internal revision number
314 returned: always
315 type: str
316 sample: "17.0.2.10658"
317 serial:
318 description: Serial number of the unit
319 returned: always
320 type: str
321 sample: "FGVMEVYYQT3AB5352"
322 status:
323 description: Indication of the operation's result
324 returned: always
325 type: str
326 sample: "success"
327 vdom:
328 description: Virtual domain used
329 returned: always
330 type: str
331 sample: "root"
332 version:
333 description: Version of the FortiGate
334 returned: always
335 type: str
336 sample: "v5.6.3"
337 """
338 from ansible.module_utils.basic import AnsibleModule
339 from ansible.module_utils.connection import Connection
340 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
341 FortiOSHandler,
342 )
343 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
344 check_legacy_fortiosapi,
345 )
346 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
347 schema_to_module_spec,
348 )
349 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
350 check_schema_versioning,
351 )
352 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
353 FAIL_SOCKET_MSG,
354 )
355 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
356 remove_invalid_fields,
357 )
358 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
359 is_same_comparison,
360 )
361 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
362 serialize,
363 )
364 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
365 find_current_values,
366 )
367 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
368 unify_data_format,
369 )
370
371
372 def filter_system_dns_data(json):
373 option_list = [
374 "alt_primary",
375 "alt_secondary",
376 "cache_notfound_responses",
377 "dns_cache_limit",
378 "dns_cache_ttl",
379 "dns_over_tls",
380 "domain",
381 "fqdn_cache_ttl",
382 "fqdn_max_refresh",
383 "fqdn_min_refresh",
384 "hostname_limit",
385 "hostname_ttl",
386 "interface",
387 "interface_select_method",
388 "ip6_primary",
389 "ip6_secondary",
390 "log",
391 "primary",
392 "protocol",
393 "retry",
394 "root_servers",
395 "secondary",
396 "server_hostname",
397 "server_select_method",
398 "source_ip",
399 "source_ip_interface",
400 "ssl_certificate",
401 "timeout",
402 "vrf_select",
403 ]
404
405 json = remove_invalid_fields(json)
406 dictionary = {}
407
408 for attribute in option_list:
409 if attribute in json and json[attribute] is not None:
410 dictionary[attribute] = json[attribute]
411
412 return dictionary
413
414
415 def flatten_single_path(data, path, index):
416 if (
417 not data
418 or index == len(path)
419 or path[index] not in data
420 or (not data[path[index]] and not isinstance(data[path[index]], list))
421 ):
422 return
423
424 if index == len(path) - 1:
425 data[path[index]] = " ".join(str(elem) for elem in data[path[index]])
426 if len(data[path[index]]) == 0:
427 data[path[index]] = None
428 elif isinstance(data[path[index]], list):
429 for value in data[path[index]]:
430 flatten_single_path(value, path, index + 1)
431 else:
432 flatten_single_path(data[path[index]], path, index + 1)
433
434
435 def flatten_multilists_attributes(data):
436 multilist_attrs = [
437 ["protocol"],
438 ["root_servers"],
439 ]
440
441 for attr in multilist_attrs:
442 flatten_single_path(data, attr, 0)
443
444 return data
445
446
447 def underscore_to_hyphen(data):
448 new_data = None
449 if isinstance(data, list):
450 new_data = []
451 for i, elem in enumerate(data):
452 new_data.append(underscore_to_hyphen(elem))
453 elif isinstance(data, dict):
454 new_data = {}
455 for k, v in data.items():
456 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
457 else:
458 return data
459 return new_data
460
461
462 def system_dns(data, fos, check_mode=False):
463
464 state = None
465 vdom = data["vdom"]
466 parameters = None
467 state = data.get("state", None)
468 system_dns_data = data["system_dns"]
469
470 filtered_data = filter_system_dns_data(system_dns_data)
471 filtered_data = flatten_multilists_attributes(filtered_data)
472 converted_data = underscore_to_hyphen(filtered_data)
473
474 # check_mode starts from here
475 if check_mode:
476 diff = {
477 "before": "",
478 "after": filtered_data,
479 }
480 mkeyname = fos.get_mkeyname(None, None)
481 mkey = fos.get_mkey("system", "dns", filtered_data, vdom=vdom)
482 current_data = fos.get(
483 "system", "dns", vdom=vdom, mkey=mkey, parameters=parameters
484 )
485 is_existed = (
486 current_data
487 and current_data.get("http_status") == 200
488 and (
489 mkeyname
490 and isinstance(current_data.get("results"), list)
491 and len(current_data["results"]) > 0
492 or not mkeyname
493 and current_data["results"] # global object response
494 )
495 )
496
497 # 2. if it exists and the state is 'present' then compare current settings with desired
498 if state == "present" or state is True or state is None:
499 # for non global modules, mkeyname must exist and it's a new module when mkey is None
500 if mkeyname is not None and mkey is None:
501 return False, True, filtered_data, diff
502
503 # if mkey exists then compare each other
504 # record exits and they're matched or not
505 copied_filtered_data = filtered_data.copy()
506 copied_filtered_data.pop(mkeyname, None)
507 unified_filtered_data = unify_data_format(copied_filtered_data)
508
509 current_data_results = current_data.get("results", {})
510 current_config = (
511 current_data_results[0]
512 if mkeyname
513 and isinstance(current_data_results, list)
514 and len(current_data_results) > 0
515 else current_data_results
516 )
517 if is_existed:
518 unified_current_values = find_current_values(
519 unified_filtered_data,
520 unify_data_format(current_config),
521 )
522
523 is_same = is_same_comparison(
524 serialize(unified_current_values), serialize(unified_filtered_data)
525 )
526
527 return (
528 False,
529 not is_same,
530 filtered_data,
531 {"before": unified_current_values, "after": unified_filtered_data},
532 )
533
534 # record does not exist
535 return False, True, filtered_data, diff
536
537 if state == "absent":
538 if mkey is None:
539 return (
540 False,
541 False,
542 filtered_data,
543 {"before": current_data["results"][0], "after": ""},
544 )
545
546 if is_existed:
547 return (
548 False,
549 True,
550 filtered_data,
551 {"before": current_data["results"][0], "after": ""},
552 )
553 return False, False, filtered_data, {}
554
555 return True, False, {"reason: ": "Must provide state parameter"}, {}
556 # pass post processed data to member operations
557 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
558 data_copy = data.copy()
559 data_copy["system_dns"] = filtered_data
560 fos.do_member_operation(
561 "system",
562 "dns",
563 data_copy,
564 )
565
566 return fos.set(
567 "system", "dns", data=converted_data, vdom=vdom, parameters=parameters
568 )
569
570
571 def is_successful_status(resp):
572 return (
573 "status" in resp
574 and resp["status"] == "success"
575 or "http_status" in resp
576 and resp["http_status"] == 200
577 or "http_method" in resp
578 and resp["http_method"] == "DELETE"
579 and resp["http_status"] == 404
580 )
581
582
583 def fortios_system(data, fos, check_mode):
584
585 if data["system_dns"]:
586 resp = system_dns(data, fos, check_mode)
587 else:
588 fos._module.fail_json(msg="missing task body: %s" % ("system_dns"))
589 if isinstance(resp, tuple) and len(resp) == 4:
590 return resp
591 return (
592 not is_successful_status(resp),
593 is_successful_status(resp)
594 and (resp["revision_changed"] if "revision_changed" in resp else True),
595 resp,
596 {},
597 )
598
599
600 versioned_schema = {
601 "v_range": [["v6.0.0", ""]],
602 "type": "dict",
603 "children": {
604 "primary": {"v_range": [["v6.0.0", ""]], "type": "string"},
605 "secondary": {"v_range": [["v6.0.0", ""]], "type": "string"},
606 "protocol": {
607 "v_range": [["v7.0.0", ""]],
608 "type": "list",
609 "options": [{"value": "cleartext"}, {"value": "dot"}, {"value": "doh"}],
610 "multiple_values": True,
611 "elements": "str",
612 },
613 "ssl_certificate": {"v_range": [["v6.2.0", ""]], "type": "string"},
614 "server_hostname": {
615 "type": "list",
616 "elements": "dict",
617 "children": {
618 "hostname": {
619 "v_range": [["v6.2.0", ""]],
620 "type": "string",
621 "required": True,
622 }
623 },
624 "v_range": [["v6.2.0", ""]],
625 },
626 "domain": {
627 "type": "list",
628 "elements": "dict",
629 "children": {
630 "domain": {
631 "v_range": [["v6.0.0", ""]],
632 "type": "string",
633 "required": True,
634 }
635 },
636 "v_range": [["v6.0.0", ""]],
637 },
638 "ip6_primary": {"v_range": [["v6.0.0", ""]], "type": "string"},
639 "ip6_secondary": {"v_range": [["v6.0.0", ""]], "type": "string"},
640 "timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
641 "retry": {"v_range": [["v6.0.0", ""]], "type": "integer"},
642 "dns_cache_limit": {"v_range": [["v6.0.0", ""]], "type": "integer"},
643 "dns_cache_ttl": {"v_range": [["v6.0.0", ""]], "type": "integer"},
644 "cache_notfound_responses": {
645 "v_range": [["v6.0.0", ""]],
646 "type": "string",
647 "options": [{"value": "disable"}, {"value": "enable"}],
648 },
649 "source_ip": {"v_range": [["v6.0.0", ""]], "type": "string"},
650 "source_ip_interface": {"v_range": [["v7.6.1", ""]], "type": "string"},
651 "root_servers": {
652 "v_range": [["v7.6.0", ""]],
653 "type": "list",
654 "multiple_values": True,
655 "elements": "str",
656 },
657 "interface_select_method": {
658 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
659 "type": "string",
660 "options": [{"value": "auto"}, {"value": "sdwan"}, {"value": "specify"}],
661 },
662 "interface": {
663 "v_range": [["v6.2.0", "v6.2.0"], ["v6.2.5", ""]],
664 "type": "string",
665 },
666 "vrf_select": {"v_range": [["v7.6.1", ""]], "type": "integer"},
667 "server_select_method": {
668 "v_range": [["v7.0.1", ""]],
669 "type": "string",
670 "options": [{"value": "least-rtt"}, {"value": "failover"}],
671 },
672 "alt_primary": {"v_range": [["v7.0.1", ""]], "type": "string"},
673 "alt_secondary": {"v_range": [["v7.0.1", ""]], "type": "string"},
674 "log": {
675 "v_range": [["v7.0.1", ""]],
676 "type": "string",
677 "options": [{"value": "disable"}, {"value": "error"}, {"value": "all"}],
678 },
679 "fqdn_cache_ttl": {"v_range": [["v7.2.1", ""]], "type": "integer"},
680 "fqdn_max_refresh": {"v_range": [["v7.4.0", ""]], "type": "integer"},
681 "fqdn_min_refresh": {"v_range": [["v7.2.1", ""]], "type": "integer"},
682 "hostname_ttl": {"v_range": [["v7.6.0", ""]], "type": "integer"},
683 "hostname_limit": {"v_range": [["v7.6.0", ""]], "type": "integer"},
684 "dns_over_tls": {
685 "v_range": [["v6.2.0", "v6.4.4"]],
686 "type": "string",
687 "options": [
688 {"value": "disable"},
689 {"value": "enable"},
690 {"value": "enforce"},
691 ],
692 },
693 },
694 }
695
696
697 def main():
698 module_spec = schema_to_module_spec(versioned_schema)
699 mkeyname = None
700 fields = {
701 "access_token": {"required": False, "type": "str", "no_log": True},
702 "enable_log": {"required": False, "type": "bool", "default": False},
703 "vdom": {"required": False, "type": "str", "default": "root"},
704 "member_path": {"required": False, "type": "str"},
705 "member_state": {
706 "type": "str",
707 "required": False,
708 "choices": ["present", "absent"],
709 },
710 "system_dns": {
711 "required": False,
712 "type": "dict",
713 "default": None,
714 "options": {},
715 },
716 }
717 for attribute_name in module_spec["options"]:
718 fields["system_dns"]["options"][attribute_name] = module_spec["options"][
719 attribute_name
720 ]
721 if mkeyname and mkeyname == attribute_name:
722 fields["system_dns"]["options"][attribute_name]["required"] = True
723
724 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
725 check_legacy_fortiosapi(module)
726
727 is_error = False
728 has_changed = False
729 result = None
730 diff = None
731
732 versions_check_result = None
733 if module._socket_path:
734 connection = Connection(module._socket_path)
735 if "access_token" in module.params:
736 connection.set_custom_option("access_token", module.params["access_token"])
737
738 if "enable_log" in module.params:
739 connection.set_custom_option("enable_log", module.params["enable_log"])
740 else:
741 connection.set_custom_option("enable_log", False)
742 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
743 versions_check_result = check_schema_versioning(
744 fos, versioned_schema, "system_dns"
745 )
746
747 is_error, has_changed, result, diff = fortios_system(
748 module.params, fos, module.check_mode
749 )
750
751 else:
752 module.fail_json(**FAIL_SOCKET_MSG)
753
754 if versions_check_result and versions_check_result["matched"] is False:
755 module.warn(
756 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
757 )
758
759 if not is_error:
760 if versions_check_result and versions_check_result["matched"] is False:
761 module.exit_json(
762 changed=has_changed,
763 version_check_warning=versions_check_result,
764 meta=result,
765 diff=diff,
766 )
767 else:
768 module.exit_json(changed=has_changed, meta=result, diff=diff)
769 else:
770 if versions_check_result and versions_check_result["matched"] is False:
771 module.fail_json(
772 msg="Error in repo",
773 version_check_warning=versions_check_result,
774 meta=result,
775 )
776 else:
777 module.fail_json(msg="Error in repo", meta=result)
778
779
780 if __name__ == "__main__":
781 main()