Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_router_static6.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_static6
23 short_description: Configure IPv6 static routing tables 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 static6 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 - We highly recommend using your own value as the seq_num instead of 0, while '0' is a special placeholder that allows the backend to assign the latest
39 available number for the object, it does have limitations. Please find more details in Q&A.
40 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
41
42 - The module supports check_mode.
43
44 requirements:
45 - ansible>=2.16
46 options:
47 access_token:
48 description:
49 - Token-based authentication.
50 Generated from GUI of Fortigate.
51 type: str
52 required: false
53 enable_log:
54 description:
55 - Enable/Disable logging for task.
56 type: bool
57 required: false
58 default: false
59 vdom:
60 description:
61 - Virtual domain, among those defined previously. A vdom is a
62 virtual instance of the FortiGate that can be configured and
63 used as a different unit.
64 type: str
65 default: root
66 member_path:
67 type: str
68 description:
69 - Member attribute path to operate on.
70 - Delimited by a slash character if there are more than one attribute.
71 - Parameter marked with member_path is legitimate for doing member operation.
72 member_state:
73 type: str
74 description:
75 - Add or delete a member under specified attribute path.
76 - When member_state is specified, the state option is ignored.
77 choices:
78 - 'present'
79 - 'absent'
80
81 state:
82 description:
83 - Indicates whether to create or remove the object.
84 type: str
85 required: true
86 choices:
87 - 'present'
88 - 'absent'
89 router_static6:
90 description:
91 - Configure IPv6 static routing tables.
92 default: null
93 type: dict
94 suboptions:
95 bfd:
96 description:
97 - Enable/disable Bidirectional Forwarding Detection (BFD).
98 type: str
99 choices:
100 - 'enable'
101 - 'disable'
102 blackhole:
103 description:
104 - Enable/disable black hole.
105 type: str
106 choices:
107 - 'enable'
108 - 'disable'
109 comment:
110 description:
111 - Optional comments.
112 type: str
113 device:
114 description:
115 - Gateway out interface or tunnel. Source system.interface.name.
116 type: str
117 devindex:
118 description:
119 - Device index (0 - 4294967295).
120 type: int
121 distance:
122 description:
123 - Administrative distance (1 - 255).
124 type: int
125 dst:
126 description:
127 - Destination IPv6 prefix.
128 type: str
129 dstaddr:
130 description:
131 - Name of firewall address or address group. Source firewall.address6.name firewall.addrgrp6.name.
132 type: str
133 dynamic_gateway:
134 description:
135 - Enable use of dynamic gateway retrieved from Router Advertisement (RA).
136 type: str
137 choices:
138 - 'enable'
139 - 'disable'
140 gateway:
141 description:
142 - IPv6 address of the gateway.
143 type: str
144 link_monitor_exempt:
145 description:
146 - Enable/disable withdrawal of this static route when link monitor or health check is down.
147 type: str
148 choices:
149 - 'enable'
150 - 'disable'
151 priority:
152 description:
153 - Administrative priority (1 - 65535).
154 type: int
155 sdwan:
156 description:
157 - Enable/disable egress through the SD-WAN.
158 type: str
159 choices:
160 - 'enable'
161 - 'disable'
162 sdwan_zone:
163 description:
164 - Choose SD-WAN Zone.
165 type: list
166 elements: dict
167 suboptions:
168 name:
169 description:
170 - SD-WAN zone name. Source system.sdwan.zone.name.
171 required: true
172 type: str
173 seq_num:
174 description:
175 - Sequence number. see <a href='#notes'>Notes</a>.
176 required: true
177 type: int
178 status:
179 description:
180 - Enable/disable this static route.
181 type: str
182 choices:
183 - 'enable'
184 - 'disable'
185 tag:
186 description:
187 - Route tag.
188 type: int
189 virtual_wan_link:
190 description:
191 - Enable/disable egress through the virtual-wan-link.
192 type: str
193 choices:
194 - 'enable'
195 - 'disable'
196 vrf:
197 description:
198 - Virtual Routing Forwarding ID.
199 type: int
200 weight:
201 description:
202 - Administrative weight (0 - 255).
203 type: int
204 """
205
206 EXAMPLES = """
207 - name: Configure IPv6 static routing tables.
208 fortinet.fortios.fortios_router_static6:
209 vdom: "{{ vdom }}"
210 state: "present"
211 access_token: "<your_own_value>"
212 router_static6:
213 bfd: "enable"
214 blackhole: "enable"
215 comment: "Optional comments."
216 device: "<your_own_value> (source system.interface.name)"
217 devindex: "0"
218 distance: "10"
219 dst: "<your_own_value>"
220 dstaddr: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)"
221 dynamic_gateway: "enable"
222 gateway: "<your_own_value>"
223 link_monitor_exempt: "enable"
224 priority: "1024"
225 sdwan: "enable"
226 sdwan_zone:
227 -
228 name: "default_name_17 (source system.sdwan.zone.name)"
229 seq_num: "<you_own_value>"
230 status: "enable"
231 tag: "0"
232 virtual_wan_link: "enable"
233 vrf: "unspecified"
234 weight: "0"
235 """
236
237 RETURN = """
238 build:
239 description: Build number of the fortigate image
240 returned: always
241 type: str
242 sample: '1547'
243 http_method:
244 description: Last method used to provision the content into FortiGate
245 returned: always
246 type: str
247 sample: 'PUT'
248 http_status:
249 description: Last result given by FortiGate on last operation applied
250 returned: always
251 type: str
252 sample: "200"
253 mkey:
254 description: Master key (id) used in the last call to FortiGate
255 returned: success
256 type: str
257 sample: "id"
258 name:
259 description: Name of the table used to fulfill the request
260 returned: always
261 type: str
262 sample: "urlfilter"
263 path:
264 description: Path of the table used to fulfill the request
265 returned: always
266 type: str
267 sample: "webfilter"
268 revision:
269 description: Internal revision number
270 returned: always
271 type: str
272 sample: "17.0.2.10658"
273 serial:
274 description: Serial number of the unit
275 returned: always
276 type: str
277 sample: "FGVMEVYYQT3AB5352"
278 status:
279 description: Indication of the operation's result
280 returned: always
281 type: str
282 sample: "success"
283 vdom:
284 description: Virtual domain used
285 returned: always
286 type: str
287 sample: "root"
288 version:
289 description: Version of the FortiGate
290 returned: always
291 type: str
292 sample: "v5.6.3"
293 """
294 from ansible.module_utils.basic import AnsibleModule
295 from ansible.module_utils.connection import Connection
296 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
297 FortiOSHandler,
298 )
299 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
300 check_legacy_fortiosapi,
301 )
302 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
303 schema_to_module_spec,
304 )
305 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
306 check_schema_versioning,
307 )
308 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
309 FAIL_SOCKET_MSG,
310 )
311 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
312 remove_invalid_fields,
313 )
314 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
315 is_same_comparison,
316 )
317 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
318 serialize,
319 )
320 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
321 find_current_values,
322 )
323 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
324 unify_data_format,
325 )
326
327
328 def filter_router_static6_data(json):
329 option_list = [
330 "bfd",
331 "blackhole",
332 "comment",
333 "device",
334 "devindex",
335 "distance",
336 "dst",
337 "dstaddr",
338 "dynamic_gateway",
339 "gateway",
340 "link_monitor_exempt",
341 "priority",
342 "sdwan",
343 "sdwan_zone",
344 "seq_num",
345 "status",
346 "tag",
347 "virtual_wan_link",
348 "vrf",
349 "weight",
350 ]
351
352 json = remove_invalid_fields(json)
353 dictionary = {}
354
355 for attribute in option_list:
356 if attribute in json and json[attribute] is not None:
357 dictionary[attribute] = json[attribute]
358
359 return dictionary
360
361
362 def underscore_to_hyphen(data):
363 new_data = None
364 if isinstance(data, list):
365 new_data = []
366 for i, elem in enumerate(data):
367 new_data.append(underscore_to_hyphen(elem))
368 elif isinstance(data, dict):
369 new_data = {}
370 for k, v in data.items():
371 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
372 else:
373 return data
374 return new_data
375
376
377 def router_static6(data, fos, check_mode=False):
378
379 state = None
380 vdom = data["vdom"]
381 parameters = None
382 state = data.get("state", None)
383 router_static6_data = data["router_static6"]
384
385 filtered_data = filter_router_static6_data(router_static6_data)
386 converted_data = underscore_to_hyphen(filtered_data)
387
388 # check_mode starts from here
389 if check_mode:
390 diff = {
391 "before": "",
392 "after": filtered_data,
393 }
394 mkeyname = fos.get_mkeyname(None, None)
395 mkey = fos.get_mkey("router", "static6", filtered_data, vdom=vdom)
396 current_data = fos.get(
397 "router", "static6", vdom=vdom, mkey=mkey, parameters=parameters
398 )
399 is_existed = (
400 current_data
401 and current_data.get("http_status") == 200
402 and (
403 mkeyname
404 and isinstance(current_data.get("results"), list)
405 and len(current_data["results"]) > 0
406 or not mkeyname
407 and current_data["results"] # global object response
408 )
409 )
410
411 # 2. if it exists and the state is 'present' then compare current settings with desired
412 if state == "present" or state is True or state is None:
413 # for non global modules, mkeyname must exist and it's a new module when mkey is None
414 if mkeyname is not None and mkey is None:
415 return False, True, filtered_data, diff
416
417 # if mkey exists then compare each other
418 # record exits and they're matched or not
419 copied_filtered_data = filtered_data.copy()
420 copied_filtered_data.pop(mkeyname, None)
421 unified_filtered_data = unify_data_format(copied_filtered_data)
422
423 current_data_results = current_data.get("results", {})
424 current_config = (
425 current_data_results[0]
426 if mkeyname
427 and isinstance(current_data_results, list)
428 and len(current_data_results) > 0
429 else current_data_results
430 )
431 if is_existed:
432 unified_current_values = find_current_values(
433 unified_filtered_data,
434 unify_data_format(current_config),
435 )
436
437 is_same = is_same_comparison(
438 serialize(unified_current_values), serialize(unified_filtered_data)
439 )
440
441 return (
442 False,
443 not is_same,
444 filtered_data,
445 {"before": unified_current_values, "after": unified_filtered_data},
446 )
447
448 # record does not exist
449 return False, True, filtered_data, diff
450
451 if state == "absent":
452 if mkey is None:
453 return (
454 False,
455 False,
456 filtered_data,
457 {"before": current_data["results"][0], "after": ""},
458 )
459
460 if is_existed:
461 return (
462 False,
463 True,
464 filtered_data,
465 {"before": current_data["results"][0], "after": ""},
466 )
467 return False, False, filtered_data, {}
468
469 return True, False, {"reason: ": "Must provide state parameter"}, {}
470 # pass post processed data to member operations
471 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
472 data_copy = data.copy()
473 data_copy["router_static6"] = filtered_data
474 fos.do_member_operation(
475 "router",
476 "static6",
477 data_copy,
478 )
479
480 if state == "present" or state is True:
481 return fos.set(
482 "router", "static6", data=converted_data, vdom=vdom, parameters=parameters
483 )
484
485 elif state == "absent":
486 return fos.delete(
487 "router",
488 "static6",
489 mkey=converted_data["seq-num"],
490 vdom=vdom,
491 parameters=parameters,
492 )
493 else:
494 fos._module.fail_json(msg="state must be present or absent!")
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_router(data, fos, check_mode):
510
511 if data["router_static6"]:
512 resp = router_static6(data, fos, check_mode)
513 else:
514 fos._module.fail_json(msg="missing task body: %s" % ("router_static6"))
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 "type": "list",
528 "elements": "dict",
529 "children": {
530 "seq_num": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
531 "status": {
532 "v_range": [["v6.0.0", ""]],
533 "type": "string",
534 "options": [{"value": "enable"}, {"value": "disable"}],
535 },
536 "dst": {"v_range": [["v6.0.0", ""]], "type": "string"},
537 "gateway": {"v_range": [["v6.0.0", ""]], "type": "string"},
538 "device": {"v_range": [["v6.0.0", ""]], "type": "string"},
539 "devindex": {"v_range": [["v6.0.0", ""]], "type": "integer"},
540 "distance": {"v_range": [["v6.0.0", ""]], "type": "integer"},
541 "weight": {"v_range": [["v7.2.1", ""]], "type": "integer"},
542 "priority": {"v_range": [["v6.0.0", ""]], "type": "integer"},
543 "comment": {"v_range": [["v6.0.0", ""]], "type": "string"},
544 "blackhole": {
545 "v_range": [["v6.0.0", ""]],
546 "type": "string",
547 "options": [{"value": "enable"}, {"value": "disable"}],
548 },
549 "dynamic_gateway": {
550 "v_range": [["v7.0.0", ""]],
551 "type": "string",
552 "options": [{"value": "enable"}, {"value": "disable"}],
553 },
554 "sdwan_zone": {
555 "type": "list",
556 "elements": "dict",
557 "children": {
558 "name": {
559 "v_range": [["v7.0.1", ""]],
560 "type": "string",
561 "required": True,
562 }
563 },
564 "v_range": [["v7.0.1", ""]],
565 },
566 "dstaddr": {"v_range": [["v7.2.1", ""]], "type": "string"},
567 "link_monitor_exempt": {
568 "v_range": [["v6.2.0", ""]],
569 "type": "string",
570 "options": [{"value": "enable"}, {"value": "disable"}],
571 },
572 "vrf": {"v_range": [["v7.0.1", ""]], "type": "integer"},
573 "bfd": {
574 "v_range": [["v6.0.0", ""]],
575 "type": "string",
576 "options": [{"value": "enable"}, {"value": "disable"}],
577 },
578 "tag": {"v_range": [["v7.6.1", ""]], "type": "integer"},
579 "sdwan": {
580 "v_range": [["v6.4.0", "v7.0.0"]],
581 "type": "string",
582 "options": [{"value": "enable"}, {"value": "disable"}],
583 },
584 "virtual_wan_link": {
585 "v_range": [["v6.0.0", "v6.2.7"]],
586 "type": "string",
587 "options": [{"value": "enable"}, {"value": "disable"}],
588 },
589 },
590 "v_range": [["v6.0.0", ""]],
591 }
592
593
594 def main():
595 module_spec = schema_to_module_spec(versioned_schema)
596 mkeyname = "seq_num"
597 fields = {
598 "access_token": {"required": False, "type": "str", "no_log": True},
599 "enable_log": {"required": False, "type": "bool", "default": False},
600 "vdom": {"required": False, "type": "str", "default": "root"},
601 "member_path": {"required": False, "type": "str"},
602 "member_state": {
603 "type": "str",
604 "required": False,
605 "choices": ["present", "absent"],
606 },
607 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
608 "router_static6": {
609 "required": False,
610 "type": "dict",
611 "default": None,
612 "options": {},
613 },
614 }
615 for attribute_name in module_spec["options"]:
616 fields["router_static6"]["options"][attribute_name] = module_spec["options"][
617 attribute_name
618 ]
619 if mkeyname and mkeyname == attribute_name:
620 fields["router_static6"]["options"][attribute_name]["required"] = True
621
622 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
623 check_legacy_fortiosapi(module)
624
625 is_error = False
626 has_changed = False
627 result = None
628 diff = None
629
630 versions_check_result = None
631 if module._socket_path:
632 connection = Connection(module._socket_path)
633 if "access_token" in module.params:
634 connection.set_custom_option("access_token", module.params["access_token"])
635
636 if "enable_log" in module.params:
637 connection.set_custom_option("enable_log", module.params["enable_log"])
638 else:
639 connection.set_custom_option("enable_log", False)
640 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
641 versions_check_result = check_schema_versioning(
642 fos, versioned_schema, "router_static6"
643 )
644
645 is_error, has_changed, result, diff = fortios_router(
646 module.params, fos, module.check_mode
647 )
648
649 else:
650 module.fail_json(**FAIL_SOCKET_MSG)
651
652 if versions_check_result and versions_check_result["matched"] is False:
653 module.warn(
654 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
655 )
656
657 if not is_error:
658 if versions_check_result and versions_check_result["matched"] is False:
659 module.exit_json(
660 changed=has_changed,
661 version_check_warning=versions_check_result,
662 meta=result,
663 diff=diff,
664 )
665 else:
666 module.exit_json(changed=has_changed, meta=result, diff=diff)
667 else:
668 if versions_check_result and versions_check_result["matched"] is False:
669 module.fail_json(
670 msg="Error in repo",
671 version_check_warning=versions_check_result,
672 meta=result,
673 )
674 else:
675 module.fail_json(msg="Error in repo", meta=result)
676
677
678 if __name__ == "__main__":
679 main()