Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_ntp.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_ntp
23 short_description: Configure system NTP information 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 ntp 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_ntp:
80 description:
81 - Configure system NTP information.
82 default: null
83 type: dict
84 suboptions:
85 authentication:
86 description:
87 - Enable/disable authentication.
88 type: str
89 choices:
90 - 'enable'
91 - 'disable'
92 interface:
93 description:
94 - FortiGate interface(s) with NTP server mode enabled. Devices on your network can contact these interfaces for NTP services.
95 type: list
96 elements: dict
97 suboptions:
98 interface_name:
99 description:
100 - Interface name. Source system.interface.name.
101 required: true
102 type: str
103 key:
104 description:
105 - Key for authentication.
106 type: str
107 key_id:
108 description:
109 - Key ID for authentication.
110 type: int
111 key_type:
112 description:
113 - Key type for authentication (MD5, SHA1, SHA256).
114 type: str
115 choices:
116 - 'MD5'
117 - 'SHA1'
118 - 'SHA256'
119 ntpserver:
120 description:
121 - Configure the FortiGate to connect to any available third-party NTP server.
122 type: list
123 elements: dict
124 suboptions:
125 authentication:
126 description:
127 - Enable/disable authentication.
128 type: str
129 choices:
130 - 'enable'
131 - 'disable'
132 id:
133 description:
134 - NTP server ID. see <a href='#notes'>Notes</a>.
135 required: true
136 type: int
137 interface:
138 description:
139 - Specify outgoing interface to reach server. Source system.interface.name.
140 type: str
141 interface_select_method:
142 description:
143 - Specify how to select outgoing interface to reach server.
144 type: str
145 choices:
146 - 'auto'
147 - 'sdwan'
148 - 'specify'
149 ip_type:
150 description:
151 - Choose to connect to IPv4 or/and IPv6 NTP server.
152 type: str
153 choices:
154 - 'IPv6'
155 - 'IPv4'
156 - 'Both'
157 key:
158 description:
159 - Key for MD5(NTPv3)/SHA1(NTPv4)/SHA256(NTPv4) authentication.
160 type: str
161 key_id:
162 description:
163 - Key ID for authentication.
164 type: int
165 key_type:
166 description:
167 - Select NTP authentication type.
168 type: str
169 choices:
170 - 'MD5'
171 - 'SHA1'
172 - 'SHA256'
173 ntpv3:
174 description:
175 - Enable to use NTPv3 instead of NTPv4.
176 type: str
177 choices:
178 - 'enable'
179 - 'disable'
180 server:
181 description:
182 - IP address or hostname of the NTP Server.
183 type: str
184 vrf_select:
185 description:
186 - VRF ID used for connection to server.
187 type: int
188 ntpsync:
189 description:
190 - Enable/disable setting the FortiGate system time by synchronizing with an NTP Server.
191 type: str
192 choices:
193 - 'enable'
194 - 'disable'
195 server_mode:
196 description:
197 - Enable/disable FortiGate NTP Server Mode. Your FortiGate becomes an NTP server for other devices on your network. The FortiGate relays
198 NTP requests to its configured NTP server.
199 type: str
200 choices:
201 - 'enable'
202 - 'disable'
203 source_ip:
204 description:
205 - Source IP address for communication to the NTP server.
206 type: str
207 source_ip6:
208 description:
209 - Source IPv6 address for communication to the NTP server.
210 type: str
211 syncinterval:
212 description:
213 - NTP synchronization interval (1 - 1440 min).
214 type: int
215 type:
216 description:
217 - Use the FortiGuard NTP server or any other available NTP Server.
218 type: str
219 choices:
220 - 'fortiguard'
221 - 'custom'
222 """
223
224 EXAMPLES = """
225 - name: Configure system NTP information.
226 fortinet.fortios.fortios_system_ntp:
227 vdom: "{{ vdom }}"
228 system_ntp:
229 authentication: "enable"
230 interface:
231 -
232 interface_name: "<your_own_value> (source system.interface.name)"
233 key: "<your_own_value>"
234 key_id: "0"
235 key_type: "MD5"
236 ntpserver:
237 -
238 authentication: "enable"
239 id: "11"
240 interface: "<your_own_value> (source system.interface.name)"
241 interface_select_method: "auto"
242 ip_type: "IPv6"
243 key: "<your_own_value>"
244 key_id: "0"
245 key_type: "MD5"
246 ntpv3: "enable"
247 server: "192.168.100.40"
248 vrf_select: "0"
249 ntpsync: "enable"
250 server_mode: "enable"
251 source_ip: "84.230.14.43"
252 source_ip6: "<your_own_value>"
253 syncinterval: "60"
254 type: "fortiguard"
255 """
256
257 RETURN = """
258 build:
259 description: Build number of the fortigate image
260 returned: always
261 type: str
262 sample: '1547'
263 http_method:
264 description: Last method used to provision the content into FortiGate
265 returned: always
266 type: str
267 sample: 'PUT'
268 http_status:
269 description: Last result given by FortiGate on last operation applied
270 returned: always
271 type: str
272 sample: "200"
273 mkey:
274 description: Master key (id) used in the last call to FortiGate
275 returned: success
276 type: str
277 sample: "id"
278 name:
279 description: Name of the table used to fulfill the request
280 returned: always
281 type: str
282 sample: "urlfilter"
283 path:
284 description: Path of the table used to fulfill the request
285 returned: always
286 type: str
287 sample: "webfilter"
288 revision:
289 description: Internal revision number
290 returned: always
291 type: str
292 sample: "17.0.2.10658"
293 serial:
294 description: Serial number of the unit
295 returned: always
296 type: str
297 sample: "FGVMEVYYQT3AB5352"
298 status:
299 description: Indication of the operation's result
300 returned: always
301 type: str
302 sample: "success"
303 vdom:
304 description: Virtual domain used
305 returned: always
306 type: str
307 sample: "root"
308 version:
309 description: Version of the FortiGate
310 returned: always
311 type: str
312 sample: "v5.6.3"
313 """
314 from ansible.module_utils.basic import AnsibleModule
315 from ansible.module_utils.connection import Connection
316 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
317 FortiOSHandler,
318 )
319 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
320 check_legacy_fortiosapi,
321 )
322 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
323 schema_to_module_spec,
324 )
325 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
326 check_schema_versioning,
327 )
328 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
329 FAIL_SOCKET_MSG,
330 )
331 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
332 remove_invalid_fields,
333 )
334 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
335 is_same_comparison,
336 )
337 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
338 serialize,
339 )
340 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
341 find_current_values,
342 )
343 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
344 unify_data_format,
345 )
346
347
348 def filter_system_ntp_data(json):
349 option_list = [
350 "authentication",
351 "interface",
352 "key",
353 "key_id",
354 "key_type",
355 "ntpserver",
356 "ntpsync",
357 "server_mode",
358 "source_ip",
359 "source_ip6",
360 "syncinterval",
361 "type",
362 ]
363
364 json = remove_invalid_fields(json)
365 dictionary = {}
366
367 for attribute in option_list:
368 if attribute in json and json[attribute] is not None:
369 dictionary[attribute] = json[attribute]
370
371 return dictionary
372
373
374 def underscore_to_hyphen(data):
375 new_data = None
376 if isinstance(data, list):
377 new_data = []
378 for i, elem in enumerate(data):
379 new_data.append(underscore_to_hyphen(elem))
380 elif isinstance(data, dict):
381 new_data = {}
382 for k, v in data.items():
383 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
384 else:
385 return data
386 return new_data
387
388
389 def system_ntp(data, fos, check_mode=False):
390
391 state = None
392 vdom = data["vdom"]
393 parameters = None
394 state = data.get("state", None)
395 system_ntp_data = data["system_ntp"]
396
397 filtered_data = filter_system_ntp_data(system_ntp_data)
398 converted_data = underscore_to_hyphen(filtered_data)
399
400 # check_mode starts from here
401 if check_mode:
402 diff = {
403 "before": "",
404 "after": filtered_data,
405 }
406 mkeyname = fos.get_mkeyname(None, None)
407 mkey = fos.get_mkey("system", "ntp", filtered_data, vdom=vdom)
408 current_data = fos.get(
409 "system", "ntp", vdom=vdom, mkey=mkey, parameters=parameters
410 )
411 is_existed = (
412 current_data
413 and current_data.get("http_status") == 200
414 and (
415 mkeyname
416 and isinstance(current_data.get("results"), list)
417 and len(current_data["results"]) > 0
418 or not mkeyname
419 and current_data["results"] # global object response
420 )
421 )
422
423 # 2. if it exists and the state is 'present' then compare current settings with desired
424 if state == "present" or state is True or state is None:
425 # for non global modules, mkeyname must exist and it's a new module when mkey is None
426 if mkeyname is not None and mkey is None:
427 return False, True, filtered_data, diff
428
429 # if mkey exists then compare each other
430 # record exits and they're matched or not
431 copied_filtered_data = filtered_data.copy()
432 copied_filtered_data.pop(mkeyname, None)
433 unified_filtered_data = unify_data_format(copied_filtered_data)
434
435 current_data_results = current_data.get("results", {})
436 current_config = (
437 current_data_results[0]
438 if mkeyname
439 and isinstance(current_data_results, list)
440 and len(current_data_results) > 0
441 else current_data_results
442 )
443 if is_existed:
444 unified_current_values = find_current_values(
445 unified_filtered_data,
446 unify_data_format(current_config),
447 )
448
449 is_same = is_same_comparison(
450 serialize(unified_current_values), serialize(unified_filtered_data)
451 )
452
453 return (
454 False,
455 not is_same,
456 filtered_data,
457 {"before": unified_current_values, "after": unified_filtered_data},
458 )
459
460 # record does not exist
461 return False, True, filtered_data, diff
462
463 if state == "absent":
464 if mkey is None:
465 return (
466 False,
467 False,
468 filtered_data,
469 {"before": current_data["results"][0], "after": ""},
470 )
471
472 if is_existed:
473 return (
474 False,
475 True,
476 filtered_data,
477 {"before": current_data["results"][0], "after": ""},
478 )
479 return False, False, filtered_data, {}
480
481 return True, False, {"reason: ": "Must provide state parameter"}, {}
482 # pass post processed data to member operations
483 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
484 data_copy = data.copy()
485 data_copy["system_ntp"] = filtered_data
486 fos.do_member_operation(
487 "system",
488 "ntp",
489 data_copy,
490 )
491
492 return fos.set(
493 "system", "ntp", data=converted_data, vdom=vdom, parameters=parameters
494 )
495
496
497 def is_successful_status(resp):
498 return (
499 "status" in resp
500 and resp["status"] == "success"
501 or "http_status" in resp
502 and resp["http_status"] == 200
503 or "http_method" in resp
504 and resp["http_method"] == "DELETE"
505 and resp["http_status"] == 404
506 )
507
508
509 def fortios_system(data, fos, check_mode):
510
511 if data["system_ntp"]:
512 resp = system_ntp(data, fos, check_mode)
513 else:
514 fos._module.fail_json(msg="missing task body: %s" % ("system_ntp"))
515 if isinstance(resp, tuple) and len(resp) == 4:
516 return resp
517 return (
518 not is_successful_status(resp),
519 is_successful_status(resp)
520 and (resp["revision_changed"] if "revision_changed" in resp else True),
521 resp,
522 {},
523 )
524
525
526 versioned_schema = {
527 "v_range": [["v6.0.0", ""]],
528 "type": "dict",
529 "children": {
530 "ntpsync": {
531 "v_range": [["v6.0.0", ""]],
532 "type": "string",
533 "options": [{"value": "enable"}, {"value": "disable"}],
534 },
535 "type": {
536 "v_range": [["v6.0.0", ""]],
537 "type": "string",
538 "options": [{"value": "fortiguard"}, {"value": "custom"}],
539 },
540 "syncinterval": {"v_range": [["v6.0.0", ""]], "type": "integer"},
541 "ntpserver": {
542 "type": "list",
543 "elements": "dict",
544 "children": {
545 "id": {
546 "v_range": [["v6.0.0", ""]],
547 "type": "integer",
548 "required": True,
549 },
550 "server": {"v_range": [["v6.0.0", ""]], "type": "string"},
551 "ntpv3": {
552 "v_range": [["v6.0.0", ""]],
553 "type": "string",
554 "options": [{"value": "enable"}, {"value": "disable"}],
555 },
556 "authentication": {
557 "v_range": [["v6.0.0", ""]],
558 "type": "string",
559 "options": [{"value": "enable"}, {"value": "disable"}],
560 },
561 "key_type": {
562 "v_range": [["v7.4.4", ""]],
563 "type": "string",
564 "options": [
565 {"value": "MD5"},
566 {"value": "SHA1"},
567 {"value": "SHA256"},
568 ],
569 },
570 "key": {"v_range": [["v6.0.0", ""]], "type": "string"},
571 "key_id": {"v_range": [["v6.0.0", ""]], "type": "integer"},
572 "ip_type": {
573 "v_range": [["v7.4.2", ""]],
574 "type": "string",
575 "options": [
576 {"value": "IPv6"},
577 {"value": "IPv4"},
578 {"value": "Both"},
579 ],
580 },
581 "interface_select_method": {
582 "v_range": [
583 ["v6.2.0", "v6.2.0"],
584 ["v6.2.5", "v6.4.0"],
585 ["v6.4.4", ""],
586 ],
587 "type": "string",
588 "options": [
589 {"value": "auto"},
590 {"value": "sdwan"},
591 {"value": "specify"},
592 ],
593 },
594 "interface": {
595 "v_range": [
596 ["v6.2.0", "v6.2.0"],
597 ["v6.2.5", "v6.4.0"],
598 ["v6.4.4", ""],
599 ],
600 "type": "string",
601 },
602 "vrf_select": {"v_range": [["v7.6.1", ""]], "type": "integer"},
603 },
604 "v_range": [["v6.0.0", ""]],
605 },
606 "source_ip": {"v_range": [["v6.0.0", ""]], "type": "string"},
607 "source_ip6": {"v_range": [["v6.0.0", ""]], "type": "string"},
608 "server_mode": {
609 "v_range": [["v6.0.0", ""]],
610 "type": "string",
611 "options": [{"value": "enable"}, {"value": "disable"}],
612 },
613 "authentication": {
614 "v_range": [["v6.2.0", ""]],
615 "type": "string",
616 "options": [{"value": "enable"}, {"value": "disable"}],
617 },
618 "key_type": {
619 "v_range": [["v6.2.0", ""]],
620 "type": "string",
621 "options": [
622 {"value": "MD5"},
623 {"value": "SHA1"},
624 {"value": "SHA256", "v_range": [["v7.4.4", ""]]},
625 ],
626 },
627 "key": {"v_range": [["v6.2.0", ""]], "type": "string"},
628 "key_id": {"v_range": [["v6.2.0", ""]], "type": "integer"},
629 "interface": {
630 "type": "list",
631 "elements": "dict",
632 "children": {
633 "interface_name": {
634 "v_range": [["v6.0.0", ""]],
635 "type": "string",
636 "required": True,
637 }
638 },
639 "v_range": [["v6.0.0", ""]],
640 },
641 },
642 }
643
644
645 def main():
646 module_spec = schema_to_module_spec(versioned_schema)
647 mkeyname = None
648 fields = {
649 "access_token": {"required": False, "type": "str", "no_log": True},
650 "enable_log": {"required": False, "type": "bool", "default": False},
651 "vdom": {"required": False, "type": "str", "default": "root"},
652 "member_path": {"required": False, "type": "str"},
653 "member_state": {
654 "type": "str",
655 "required": False,
656 "choices": ["present", "absent"],
657 },
658 "system_ntp": {
659 "required": False,
660 "type": "dict",
661 "default": None,
662 "options": {},
663 },
664 }
665 for attribute_name in module_spec["options"]:
666 fields["system_ntp"]["options"][attribute_name] = module_spec["options"][
667 attribute_name
668 ]
669 if mkeyname and mkeyname == attribute_name:
670 fields["system_ntp"]["options"][attribute_name]["required"] = True
671
672 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
673 check_legacy_fortiosapi(module)
674
675 is_error = False
676 has_changed = False
677 result = None
678 diff = None
679
680 versions_check_result = None
681 if module._socket_path:
682 connection = Connection(module._socket_path)
683 if "access_token" in module.params:
684 connection.set_custom_option("access_token", module.params["access_token"])
685
686 if "enable_log" in module.params:
687 connection.set_custom_option("enable_log", module.params["enable_log"])
688 else:
689 connection.set_custom_option("enable_log", False)
690 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
691 versions_check_result = check_schema_versioning(
692 fos, versioned_schema, "system_ntp"
693 )
694
695 is_error, has_changed, result, diff = fortios_system(
696 module.params, fos, module.check_mode
697 )
698
699 else:
700 module.fail_json(**FAIL_SOCKET_MSG)
701
702 if versions_check_result and versions_check_result["matched"] is False:
703 module.warn(
704 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
705 )
706
707 if not is_error:
708 if versions_check_result and versions_check_result["matched"] is False:
709 module.exit_json(
710 changed=has_changed,
711 version_check_warning=versions_check_result,
712 meta=result,
713 diff=diff,
714 )
715 else:
716 module.exit_json(changed=has_changed, meta=result, diff=diff)
717 else:
718 if versions_check_result and versions_check_result["matched"] is False:
719 module.fail_json(
720 msg="Error in repo",
721 version_check_warning=versions_check_result,
722 meta=result,
723 )
724 else:
725 module.fail_json(msg="Error in repo", meta=result)
726
727
728 if __name__ == "__main__":
729 main()