Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_router_static.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_static
23 short_description: Configure IPv4 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 static 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_static:
90 description:
91 - Configure IPv4 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 distance:
118 description:
119 - Administrative distance (1 - 255).
120 type: int
121 dst:
122 description:
123 - Destination IP and mask for this route.
124 type: str
125 dstaddr:
126 description:
127 - Name of firewall address or address group. Source firewall.address.name firewall.addrgrp.name.
128 type: str
129 dynamic_gateway:
130 description:
131 - Enable use of dynamic gateway retrieved from a DHCP or PPP server.
132 type: str
133 choices:
134 - 'enable'
135 - 'disable'
136 gateway:
137 description:
138 - Gateway IP for this route.
139 type: str
140 internet_service:
141 description:
142 - Application ID in the Internet service database. Source firewall.internet-service.id.
143 type: int
144 internet_service_custom:
145 description:
146 - Application name in the Internet service custom database. Source firewall.internet-service-custom.name.
147 type: str
148 internet_service_fortiguard:
149 description:
150 - Application name in the Internet service fortiguard database. Source firewall.internet-service-fortiguard.name.
151 type: str
152 link_monitor_exempt:
153 description:
154 - Enable/disable withdrawal of this static route when link monitor or health check is down.
155 type: str
156 choices:
157 - 'enable'
158 - 'disable'
159 preferred_source:
160 description:
161 - Preferred source IP for this route.
162 type: str
163 priority:
164 description:
165 - Administrative priority (1 - 65535).
166 type: int
167 sdwan:
168 description:
169 - Enable/disable egress through SD-WAN.
170 type: str
171 choices:
172 - 'enable'
173 - 'disable'
174 sdwan_zone:
175 description:
176 - Choose SD-WAN Zone.
177 type: list
178 elements: dict
179 suboptions:
180 name:
181 description:
182 - SD-WAN zone name. Source system.sdwan.zone.name.
183 required: true
184 type: str
185 seq_num:
186 description:
187 - Sequence number. see <a href='#notes'>Notes</a>.
188 required: true
189 type: int
190 src:
191 description:
192 - Source prefix for this route.
193 type: str
194 status:
195 description:
196 - Enable/disable this static route.
197 type: str
198 choices:
199 - 'enable'
200 - 'disable'
201 tag:
202 description:
203 - Route tag.
204 type: int
205 virtual_wan_link:
206 description:
207 - Enable/disable egress through the virtual-wan-link.
208 type: str
209 choices:
210 - 'enable'
211 - 'disable'
212 vrf:
213 description:
214 - Virtual Routing Forwarding ID.
215 type: int
216 weight:
217 description:
218 - Administrative weight (0 - 255).
219 type: int
220 """
221
222 EXAMPLES = """
223 - name: Configure IPv4 static routing tables.
224 fortinet.fortios.fortios_router_static:
225 vdom: "{{ vdom }}"
226 state: "present"
227 access_token: "<your_own_value>"
228 router_static:
229 bfd: "enable"
230 blackhole: "enable"
231 comment: "Optional comments."
232 device: "<your_own_value> (source system.interface.name)"
233 distance: "10"
234 dst: "<your_own_value>"
235 dstaddr: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)"
236 dynamic_gateway: "enable"
237 gateway: "<your_own_value>"
238 internet_service: "0"
239 internet_service_custom: "<your_own_value> (source firewall.internet-service-custom.name)"
240 internet_service_fortiguard: "<your_own_value> (source firewall.internet-service-fortiguard.name)"
241 link_monitor_exempt: "enable"
242 preferred_source: "<your_own_value>"
243 priority: "1"
244 sdwan: "enable"
245 sdwan_zone:
246 -
247 name: "default_name_20 (source system.sdwan.zone.name)"
248 seq_num: "<you_own_value>"
249 src: "<your_own_value>"
250 status: "enable"
251 tag: "0"
252 virtual_wan_link: "enable"
253 vrf: "unspecified"
254 weight: "0"
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_router_static_data(json):
349 option_list = [
350 "bfd",
351 "blackhole",
352 "comment",
353 "device",
354 "distance",
355 "dst",
356 "dstaddr",
357 "dynamic_gateway",
358 "gateway",
359 "internet_service",
360 "internet_service_custom",
361 "internet_service_fortiguard",
362 "link_monitor_exempt",
363 "preferred_source",
364 "priority",
365 "sdwan",
366 "sdwan_zone",
367 "seq_num",
368 "src",
369 "status",
370 "tag",
371 "virtual_wan_link",
372 "vrf",
373 "weight",
374 ]
375
376 json = remove_invalid_fields(json)
377 dictionary = {}
378
379 for attribute in option_list:
380 if attribute in json and json[attribute] is not None:
381 dictionary[attribute] = json[attribute]
382
383 return dictionary
384
385
386 def underscore_to_hyphen(data):
387 new_data = None
388 if isinstance(data, list):
389 new_data = []
390 for i, elem in enumerate(data):
391 new_data.append(underscore_to_hyphen(elem))
392 elif isinstance(data, dict):
393 new_data = {}
394 for k, v in data.items():
395 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
396 else:
397 return data
398 return new_data
399
400
401 def router_static(data, fos, check_mode=False):
402
403 state = None
404 vdom = data["vdom"]
405 parameters = None
406 state = data.get("state", None)
407 router_static_data = data["router_static"]
408
409 filtered_data = filter_router_static_data(router_static_data)
410 converted_data = underscore_to_hyphen(filtered_data)
411
412 # check_mode starts from here
413 if check_mode:
414 diff = {
415 "before": "",
416 "after": filtered_data,
417 }
418 mkeyname = fos.get_mkeyname(None, None)
419 mkey = fos.get_mkey("router", "static", filtered_data, vdom=vdom)
420 current_data = fos.get(
421 "router", "static", vdom=vdom, mkey=mkey, parameters=parameters
422 )
423 is_existed = (
424 current_data
425 and current_data.get("http_status") == 200
426 and (
427 mkeyname
428 and isinstance(current_data.get("results"), list)
429 and len(current_data["results"]) > 0
430 or not mkeyname
431 and current_data["results"] # global object response
432 )
433 )
434
435 # 2. if it exists and the state is 'present' then compare current settings with desired
436 if state == "present" or state is True or state is None:
437 # for non global modules, mkeyname must exist and it's a new module when mkey is None
438 if mkeyname is not None and mkey is None:
439 return False, True, filtered_data, diff
440
441 # if mkey exists then compare each other
442 # record exits and they're matched or not
443 copied_filtered_data = filtered_data.copy()
444 copied_filtered_data.pop(mkeyname, None)
445 unified_filtered_data = unify_data_format(copied_filtered_data)
446
447 current_data_results = current_data.get("results", {})
448 current_config = (
449 current_data_results[0]
450 if mkeyname
451 and isinstance(current_data_results, list)
452 and len(current_data_results) > 0
453 else current_data_results
454 )
455 if is_existed:
456 unified_current_values = find_current_values(
457 unified_filtered_data,
458 unify_data_format(current_config),
459 )
460
461 is_same = is_same_comparison(
462 serialize(unified_current_values), serialize(unified_filtered_data)
463 )
464
465 return (
466 False,
467 not is_same,
468 filtered_data,
469 {"before": unified_current_values, "after": unified_filtered_data},
470 )
471
472 # record does not exist
473 return False, True, filtered_data, diff
474
475 if state == "absent":
476 if mkey is None:
477 return (
478 False,
479 False,
480 filtered_data,
481 {"before": current_data["results"][0], "after": ""},
482 )
483
484 if is_existed:
485 return (
486 False,
487 True,
488 filtered_data,
489 {"before": current_data["results"][0], "after": ""},
490 )
491 return False, False, filtered_data, {}
492
493 return True, False, {"reason: ": "Must provide state parameter"}, {}
494 # pass post processed data to member operations
495 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
496 data_copy = data.copy()
497 data_copy["router_static"] = filtered_data
498 fos.do_member_operation(
499 "router",
500 "static",
501 data_copy,
502 )
503
504 if state == "present" or state is True:
505 return fos.set(
506 "router", "static", data=converted_data, vdom=vdom, parameters=parameters
507 )
508
509 elif state == "absent":
510 return fos.delete(
511 "router",
512 "static",
513 mkey=converted_data["seq-num"],
514 vdom=vdom,
515 parameters=parameters,
516 )
517 else:
518 fos._module.fail_json(msg="state must be present or absent!")
519
520
521 def is_successful_status(resp):
522 return (
523 "status" in resp
524 and resp["status"] == "success"
525 or "http_status" in resp
526 and resp["http_status"] == 200
527 or "http_method" in resp
528 and resp["http_method"] == "DELETE"
529 and resp["http_status"] == 404
530 )
531
532
533 def fortios_router(data, fos, check_mode):
534
535 if data["router_static"]:
536 resp = router_static(data, fos, check_mode)
537 else:
538 fos._module.fail_json(msg="missing task body: %s" % ("router_static"))
539 if isinstance(resp, tuple) and len(resp) == 4:
540 return resp
541 return (
542 not is_successful_status(resp),
543 is_successful_status(resp)
544 and (resp["revision_changed"] if "revision_changed" in resp else True),
545 resp,
546 {},
547 )
548
549
550 versioned_schema = {
551 "type": "list",
552 "elements": "dict",
553 "children": {
554 "seq_num": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
555 "status": {
556 "v_range": [["v6.0.0", ""]],
557 "type": "string",
558 "options": [{"value": "enable"}, {"value": "disable"}],
559 },
560 "dst": {"v_range": [["v6.0.0", ""]], "type": "string"},
561 "src": {"v_range": [["v6.0.0", ""]], "type": "string"},
562 "gateway": {"v_range": [["v6.0.0", ""]], "type": "string"},
563 "preferred_source": {"v_range": [["v7.4.0", ""]], "type": "string"},
564 "distance": {"v_range": [["v6.0.0", ""]], "type": "integer"},
565 "weight": {"v_range": [["v6.0.0", ""]], "type": "integer"},
566 "priority": {"v_range": [["v6.0.0", ""]], "type": "integer"},
567 "device": {"v_range": [["v6.0.0", ""]], "type": "string"},
568 "comment": {"v_range": [["v6.0.0", ""]], "type": "string"},
569 "blackhole": {
570 "v_range": [["v6.0.0", ""]],
571 "type": "string",
572 "options": [{"value": "enable"}, {"value": "disable"}],
573 },
574 "dynamic_gateway": {
575 "v_range": [["v6.0.0", ""]],
576 "type": "string",
577 "options": [{"value": "enable"}, {"value": "disable"}],
578 },
579 "sdwan_zone": {
580 "type": "list",
581 "elements": "dict",
582 "children": {
583 "name": {
584 "v_range": [["v7.0.1", ""]],
585 "type": "string",
586 "required": True,
587 }
588 },
589 "v_range": [["v7.0.1", ""]],
590 },
591 "dstaddr": {"v_range": [["v6.0.0", ""]], "type": "string"},
592 "internet_service": {"v_range": [["v6.0.0", ""]], "type": "integer"},
593 "internet_service_custom": {"v_range": [["v6.0.0", ""]], "type": "string"},
594 "internet_service_fortiguard": {"v_range": [["v7.6.4", ""]], "type": "string"},
595 "link_monitor_exempt": {
596 "v_range": [["v6.0.0", ""]],
597 "type": "string",
598 "options": [{"value": "enable"}, {"value": "disable"}],
599 },
600 "tag": {"v_range": [["v7.2.4", ""]], "type": "integer"},
601 "vrf": {"v_range": [["v6.0.0", ""]], "type": "integer"},
602 "bfd": {
603 "v_range": [["v6.0.0", ""]],
604 "type": "string",
605 "options": [{"value": "enable"}, {"value": "disable"}],
606 },
607 "sdwan": {
608 "v_range": [["v6.4.0", "v7.0.0"]],
609 "type": "string",
610 "options": [{"value": "enable"}, {"value": "disable"}],
611 },
612 "virtual_wan_link": {
613 "v_range": [["v6.0.0", "v6.2.7"]],
614 "type": "string",
615 "options": [{"value": "enable"}, {"value": "disable"}],
616 },
617 },
618 "v_range": [["v6.0.0", ""]],
619 }
620
621
622 def main():
623 module_spec = schema_to_module_spec(versioned_schema)
624 mkeyname = "seq_num"
625 fields = {
626 "access_token": {"required": False, "type": "str", "no_log": True},
627 "enable_log": {"required": False, "type": "bool", "default": False},
628 "vdom": {"required": False, "type": "str", "default": "root"},
629 "member_path": {"required": False, "type": "str"},
630 "member_state": {
631 "type": "str",
632 "required": False,
633 "choices": ["present", "absent"],
634 },
635 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
636 "router_static": {
637 "required": False,
638 "type": "dict",
639 "default": None,
640 "options": {},
641 },
642 }
643 for attribute_name in module_spec["options"]:
644 fields["router_static"]["options"][attribute_name] = module_spec["options"][
645 attribute_name
646 ]
647 if mkeyname and mkeyname == attribute_name:
648 fields["router_static"]["options"][attribute_name]["required"] = True
649
650 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
651 check_legacy_fortiosapi(module)
652
653 is_error = False
654 has_changed = False
655 result = None
656 diff = None
657
658 versions_check_result = None
659 if module._socket_path:
660 connection = Connection(module._socket_path)
661 if "access_token" in module.params:
662 connection.set_custom_option("access_token", module.params["access_token"])
663
664 if "enable_log" in module.params:
665 connection.set_custom_option("enable_log", module.params["enable_log"])
666 else:
667 connection.set_custom_option("enable_log", False)
668 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
669 versions_check_result = check_schema_versioning(
670 fos, versioned_schema, "router_static"
671 )
672
673 is_error, has_changed, result, diff = fortios_router(
674 module.params, fos, module.check_mode
675 )
676
677 else:
678 module.fail_json(**FAIL_SOCKET_MSG)
679
680 if versions_check_result and versions_check_result["matched"] is False:
681 module.warn(
682 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
683 )
684
685 if not is_error:
686 if versions_check_result and versions_check_result["matched"] is False:
687 module.exit_json(
688 changed=has_changed,
689 version_check_warning=versions_check_result,
690 meta=result,
691 diff=diff,
692 )
693 else:
694 module.exit_json(changed=has_changed, meta=result, diff=diff)
695 else:
696 if versions_check_result and versions_check_result["matched"] is False:
697 module.fail_json(
698 msg="Error in repo",
699 version_check_warning=versions_check_result,
700 meta=result,
701 )
702 else:
703 module.fail_json(msg="Error in repo", meta=result)
704
705
706 if __name__ == "__main__":
707 main()