Debian Codegraph @

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