Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_ptp.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_ptp
23 short_description: Configure system PTP 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 ptp 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_ptp:
80 description:
81 - Configure system PTP information.
82 default: null
83 type: dict
84 suboptions:
85 delay_mechanism:
86 description:
87 - End to end delay detection or peer to peer delay detection.
88 type: str
89 choices:
90 - 'E2E'
91 - 'P2P'
92 interface:
93 description:
94 - PTP client will reply through this interface. Source system.interface.name.
95 type: str
96 mode:
97 description:
98 - Multicast transmission or hybrid transmission.
99 type: str
100 choices:
101 - 'multicast'
102 - 'hybrid'
103 request_interval:
104 description:
105 - The delay request value is the logarithmic mean interval in seconds between the delay request messages sent by the slave to the master.
106 type: int
107 server_interface:
108 description:
109 - FortiGate interface(s) with PTP server mode enabled. Devices on your network can contact these interfaces for PTP services.
110 type: list
111 elements: dict
112 suboptions:
113 delay_mechanism:
114 description:
115 - End to end delay detection or peer to peer delay detection.
116 type: str
117 choices:
118 - 'E2E'
119 - 'P2P'
120 id:
121 description:
122 - ID. see <a href='#notes'>Notes</a>.
123 required: true
124 type: int
125 server_interface_name:
126 description:
127 - Interface name. Source system.interface.name.
128 type: str
129 server_mode:
130 description:
131 - Enable/disable FortiGate PTP server mode. Your FortiGate becomes an PTP server for other devices on your network.
132 type: str
133 choices:
134 - 'enable'
135 - 'disable'
136 status:
137 description:
138 - Enable/disable setting the FortiGate system time by synchronizing with an PTP Server.
139 type: str
140 choices:
141 - 'enable'
142 - 'disable'
143 """
144
145 EXAMPLES = """
146 - name: Configure system PTP information.
147 fortinet.fortios.fortios_system_ptp:
148 vdom: "{{ vdom }}"
149 system_ptp:
150 delay_mechanism: "E2E"
151 interface: "<your_own_value> (source system.interface.name)"
152 mode: "multicast"
153 request_interval: "1"
154 server_interface:
155 -
156 delay_mechanism: "E2E"
157 id: "9"
158 server_interface_name: "<your_own_value> (source system.interface.name)"
159 server_mode: "enable"
160 status: "enable"
161 """
162
163 RETURN = """
164 build:
165 description: Build number of the fortigate image
166 returned: always
167 type: str
168 sample: '1547'
169 http_method:
170 description: Last method used to provision the content into FortiGate
171 returned: always
172 type: str
173 sample: 'PUT'
174 http_status:
175 description: Last result given by FortiGate on last operation applied
176 returned: always
177 type: str
178 sample: "200"
179 mkey:
180 description: Master key (id) used in the last call to FortiGate
181 returned: success
182 type: str
183 sample: "id"
184 name:
185 description: Name of the table used to fulfill the request
186 returned: always
187 type: str
188 sample: "urlfilter"
189 path:
190 description: Path of the table used to fulfill the request
191 returned: always
192 type: str
193 sample: "webfilter"
194 revision:
195 description: Internal revision number
196 returned: always
197 type: str
198 sample: "17.0.2.10658"
199 serial:
200 description: Serial number of the unit
201 returned: always
202 type: str
203 sample: "FGVMEVYYQT3AB5352"
204 status:
205 description: Indication of the operation's result
206 returned: always
207 type: str
208 sample: "success"
209 vdom:
210 description: Virtual domain used
211 returned: always
212 type: str
213 sample: "root"
214 version:
215 description: Version of the FortiGate
216 returned: always
217 type: str
218 sample: "v5.6.3"
219 """
220 from ansible.module_utils.basic import AnsibleModule
221 from ansible.module_utils.connection import Connection
222 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
223 FortiOSHandler,
224 )
225 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
226 check_legacy_fortiosapi,
227 )
228 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
229 schema_to_module_spec,
230 )
231 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
232 check_schema_versioning,
233 )
234 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
235 FAIL_SOCKET_MSG,
236 )
237 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
238 remove_invalid_fields,
239 )
240 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
241 is_same_comparison,
242 )
243 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
244 serialize,
245 )
246 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
247 find_current_values,
248 )
249 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
250 unify_data_format,
251 )
252
253
254 def filter_system_ptp_data(json):
255 option_list = [
256 "delay_mechanism",
257 "interface",
258 "mode",
259 "request_interval",
260 "server_interface",
261 "server_mode",
262 "status",
263 ]
264
265 json = remove_invalid_fields(json)
266 dictionary = {}
267
268 for attribute in option_list:
269 if attribute in json and json[attribute] is not None:
270 dictionary[attribute] = json[attribute]
271
272 return dictionary
273
274
275 def underscore_to_hyphen(data):
276 new_data = None
277 if isinstance(data, list):
278 new_data = []
279 for i, elem in enumerate(data):
280 new_data.append(underscore_to_hyphen(elem))
281 elif isinstance(data, dict):
282 new_data = {}
283 for k, v in data.items():
284 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
285 else:
286 return data
287 return new_data
288
289
290 def system_ptp(data, fos, check_mode=False):
291
292 state = None
293 vdom = data["vdom"]
294 parameters = None
295 state = data.get("state", None)
296 system_ptp_data = data["system_ptp"]
297
298 filtered_data = filter_system_ptp_data(system_ptp_data)
299 converted_data = underscore_to_hyphen(filtered_data)
300
301 # check_mode starts from here
302 if check_mode:
303 diff = {
304 "before": "",
305 "after": filtered_data,
306 }
307 mkeyname = fos.get_mkeyname(None, None)
308 mkey = fos.get_mkey("system", "ptp", filtered_data, vdom=vdom)
309 current_data = fos.get(
310 "system", "ptp", vdom=vdom, mkey=mkey, parameters=parameters
311 )
312 is_existed = (
313 current_data
314 and current_data.get("http_status") == 200
315 and (
316 mkeyname
317 and isinstance(current_data.get("results"), list)
318 and len(current_data["results"]) > 0
319 or not mkeyname
320 and current_data["results"] # global object response
321 )
322 )
323
324 # 2. if it exists and the state is 'present' then compare current settings with desired
325 if state == "present" or state is True or state is None:
326 # for non global modules, mkeyname must exist and it's a new module when mkey is None
327 if mkeyname is not None and mkey is None:
328 return False, True, filtered_data, diff
329
330 # if mkey exists then compare each other
331 # record exits and they're matched or not
332 copied_filtered_data = filtered_data.copy()
333 copied_filtered_data.pop(mkeyname, None)
334 unified_filtered_data = unify_data_format(copied_filtered_data)
335
336 current_data_results = current_data.get("results", {})
337 current_config = (
338 current_data_results[0]
339 if mkeyname
340 and isinstance(current_data_results, list)
341 and len(current_data_results) > 0
342 else current_data_results
343 )
344 if is_existed:
345 unified_current_values = find_current_values(
346 unified_filtered_data,
347 unify_data_format(current_config),
348 )
349
350 is_same = is_same_comparison(
351 serialize(unified_current_values), serialize(unified_filtered_data)
352 )
353
354 return (
355 False,
356 not is_same,
357 filtered_data,
358 {"before": unified_current_values, "after": unified_filtered_data},
359 )
360
361 # record does not exist
362 return False, True, filtered_data, diff
363
364 if state == "absent":
365 if mkey is None:
366 return (
367 False,
368 False,
369 filtered_data,
370 {"before": current_data["results"][0], "after": ""},
371 )
372
373 if is_existed:
374 return (
375 False,
376 True,
377 filtered_data,
378 {"before": current_data["results"][0], "after": ""},
379 )
380 return False, False, filtered_data, {}
381
382 return True, False, {"reason: ": "Must provide state parameter"}, {}
383 # pass post processed data to member operations
384 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
385 data_copy = data.copy()
386 data_copy["system_ptp"] = filtered_data
387 fos.do_member_operation(
388 "system",
389 "ptp",
390 data_copy,
391 )
392
393 return fos.set(
394 "system", "ptp", data=converted_data, vdom=vdom, parameters=parameters
395 )
396
397
398 def is_successful_status(resp):
399 return (
400 "status" in resp
401 and resp["status"] == "success"
402 or "http_status" in resp
403 and resp["http_status"] == 200
404 or "http_method" in resp
405 and resp["http_method"] == "DELETE"
406 and resp["http_status"] == 404
407 )
408
409
410 def fortios_system(data, fos, check_mode):
411
412 if data["system_ptp"]:
413 resp = system_ptp(data, fos, check_mode)
414 else:
415 fos._module.fail_json(msg="missing task body: %s" % ("system_ptp"))
416 if isinstance(resp, tuple) and len(resp) == 4:
417 return resp
418 return (
419 not is_successful_status(resp),
420 is_successful_status(resp)
421 and (resp["revision_changed"] if "revision_changed" in resp else True),
422 resp,
423 {},
424 )
425
426
427 versioned_schema = {
428 "v_range": [["v6.2.0", ""]],
429 "type": "dict",
430 "children": {
431 "status": {
432 "v_range": [["v6.2.0", ""]],
433 "type": "string",
434 "options": [{"value": "enable"}, {"value": "disable"}],
435 },
436 "mode": {
437 "v_range": [["v6.2.0", ""]],
438 "type": "string",
439 "options": [{"value": "multicast"}, {"value": "hybrid"}],
440 },
441 "delay_mechanism": {
442 "v_range": [["v6.2.0", ""]],
443 "type": "string",
444 "options": [{"value": "E2E"}, {"value": "P2P"}],
445 },
446 "request_interval": {"v_range": [["v6.2.0", ""]], "type": "integer"},
447 "interface": {"v_range": [["v6.2.0", ""]], "type": "string"},
448 "server_mode": {
449 "v_range": [["v7.0.1", ""]],
450 "type": "string",
451 "options": [{"value": "enable"}, {"value": "disable"}],
452 },
453 "server_interface": {
454 "type": "list",
455 "elements": "dict",
456 "children": {
457 "id": {
458 "v_range": [["v7.0.1", ""]],
459 "type": "integer",
460 "required": True,
461 },
462 "server_interface_name": {
463 "v_range": [["v7.0.1", ""]],
464 "type": "string",
465 },
466 "delay_mechanism": {
467 "v_range": [["v7.0.1", ""]],
468 "type": "string",
469 "options": [{"value": "E2E"}, {"value": "P2P"}],
470 },
471 },
472 "v_range": [["v7.0.1", ""]],
473 },
474 },
475 }
476
477
478 def main():
479 module_spec = schema_to_module_spec(versioned_schema)
480 mkeyname = None
481 fields = {
482 "access_token": {"required": False, "type": "str", "no_log": True},
483 "enable_log": {"required": False, "type": "bool", "default": False},
484 "vdom": {"required": False, "type": "str", "default": "root"},
485 "member_path": {"required": False, "type": "str"},
486 "member_state": {
487 "type": "str",
488 "required": False,
489 "choices": ["present", "absent"],
490 },
491 "system_ptp": {
492 "required": False,
493 "type": "dict",
494 "default": None,
495 "options": {},
496 },
497 }
498 for attribute_name in module_spec["options"]:
499 fields["system_ptp"]["options"][attribute_name] = module_spec["options"][
500 attribute_name
501 ]
502 if mkeyname and mkeyname == attribute_name:
503 fields["system_ptp"]["options"][attribute_name]["required"] = True
504
505 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
506 check_legacy_fortiosapi(module)
507
508 is_error = False
509 has_changed = False
510 result = None
511 diff = None
512
513 versions_check_result = None
514 if module._socket_path:
515 connection = Connection(module._socket_path)
516 if "access_token" in module.params:
517 connection.set_custom_option("access_token", module.params["access_token"])
518
519 if "enable_log" in module.params:
520 connection.set_custom_option("enable_log", module.params["enable_log"])
521 else:
522 connection.set_custom_option("enable_log", False)
523 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
524 versions_check_result = check_schema_versioning(
525 fos, versioned_schema, "system_ptp"
526 )
527
528 is_error, has_changed, result, diff = fortios_system(
529 module.params, fos, module.check_mode
530 )
531
532 else:
533 module.fail_json(**FAIL_SOCKET_MSG)
534
535 if versions_check_result and versions_check_result["matched"] is False:
536 module.warn(
537 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
538 )
539
540 if not is_error:
541 if versions_check_result and versions_check_result["matched"] is False:
542 module.exit_json(
543 changed=has_changed,
544 version_check_warning=versions_check_result,
545 meta=result,
546 diff=diff,
547 )
548 else:
549 module.exit_json(changed=has_changed, meta=result, diff=diff)
550 else:
551 if versions_check_result and versions_check_result["matched"] is False:
552 module.fail_json(
553 msg="Error in repo",
554 version_check_warning=versions_check_result,
555 meta=result,
556 )
557 else:
558 module.fail_json(msg="Error in repo", meta=result)
559
560
561 if __name__ == "__main__":
562 main()