Debian Codegraph @

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