Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_router_policy.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_policy
23 short_description: Configure IPv4 routing policies 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 policy 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_policy:
90 description:
91 - Configure IPv4 routing policies.
92 default: null
93 type: dict
94 suboptions:
95 action:
96 description:
97 - Action of the policy route.
98 type: str
99 choices:
100 - 'deny'
101 - 'permit'
102 comments:
103 description:
104 - Optional comments.
105 type: str
106 dst:
107 description:
108 - Destination IP and mask (x.x.x.x/x).
109 type: list
110 elements: dict
111 suboptions:
112 subnet:
113 description:
114 - IP and mask.
115 required: true
116 type: str
117 dst_negate:
118 description:
119 - Enable/disable negating destination address match.
120 type: str
121 choices:
122 - 'enable'
123 - 'disable'
124 dstaddr:
125 description:
126 - Destination address name.
127 type: list
128 elements: dict
129 suboptions:
130 name:
131 description:
132 - Address/group name. Source firewall.address.name firewall.addrgrp.name.
133 required: true
134 type: str
135 end_port:
136 description:
137 - End destination port number (0 - 65535).
138 type: int
139 end_source_port:
140 description:
141 - End source port number (0 - 65535).
142 type: int
143 gateway:
144 description:
145 - IP address of the gateway.
146 type: str
147 groups:
148 description:
149 - List of user groups.
150 type: list
151 elements: dict
152 suboptions:
153 name:
154 description:
155 - Group name. Source user.group.name.
156 required: true
157 type: str
158 input_device:
159 description:
160 - Incoming interface name.
161 type: list
162 elements: dict
163 suboptions:
164 name:
165 description:
166 - Interface name. Source system.interface.name.
167 required: true
168 type: str
169 input_device_negate:
170 description:
171 - Enable/disable negation of input device match.
172 type: str
173 choices:
174 - 'enable'
175 - 'disable'
176 internet_service_custom:
177 description:
178 - Custom Destination Internet Service name.
179 type: list
180 elements: dict
181 suboptions:
182 name:
183 description:
184 - Custom Destination Internet Service name. Source firewall.internet-service-custom.name.
185 required: true
186 type: str
187 internet_service_fortiguard:
188 description:
189 - FortiGuard Destination Internet Service name.
190 type: list
191 elements: dict
192 suboptions:
193 name:
194 description:
195 - FortiGuard Destination Internet Service name. Source firewall.internet-service-fortiguard.name.
196 required: true
197 type: str
198 internet_service_id:
199 description:
200 - Destination Internet Service ID.
201 type: list
202 elements: dict
203 suboptions:
204 id:
205 description:
206 - Destination Internet Service ID. see <a href='#notes'>Notes</a>. Source firewall.internet-service.id.
207 required: true
208 type: int
209 output_device:
210 description:
211 - Outgoing interface name. Source system.interface.name.
212 type: str
213 protocol:
214 description:
215 - Protocol number (0 - 255).
216 type: int
217 seq_num:
218 description:
219 - Sequence number(1-65535). see <a href='#notes'>Notes</a>.
220 required: true
221 type: int
222 src:
223 description:
224 - Source IP and mask (x.x.x.x/x).
225 type: list
226 elements: dict
227 suboptions:
228 subnet:
229 description:
230 - IP and mask.
231 required: true
232 type: str
233 src_negate:
234 description:
235 - Enable/disable negating source address match.
236 type: str
237 choices:
238 - 'enable'
239 - 'disable'
240 srcaddr:
241 description:
242 - Source address name.
243 type: list
244 elements: dict
245 suboptions:
246 name:
247 description:
248 - Address/group name. Source firewall.address.name firewall.addrgrp.name.
249 required: true
250 type: str
251 start_port:
252 description:
253 - Start destination port number (0 - 65535).
254 type: int
255 start_source_port:
256 description:
257 - Start source port number (0 - 65535).
258 type: int
259 status:
260 description:
261 - Enable/disable this policy route.
262 type: str
263 choices:
264 - 'enable'
265 - 'disable'
266 tos:
267 description:
268 - Type of service bit pattern.
269 type: str
270 tos_mask:
271 description:
272 - Type of service evaluated bits.
273 type: str
274 users:
275 description:
276 - List of users.
277 type: list
278 elements: dict
279 suboptions:
280 name:
281 description:
282 - User name. Source user.local.name.
283 required: true
284 type: str
285 """
286
287 EXAMPLES = """
288 - name: Configure IPv4 routing policies.
289 fortinet.fortios.fortios_router_policy:
290 vdom: "{{ vdom }}"
291 state: "present"
292 access_token: "<your_own_value>"
293 router_policy:
294 action: "deny"
295 comments: "<your_own_value>"
296 dst:
297 -
298 subnet: "<your_own_value>"
299 dst_negate: "enable"
300 dstaddr:
301 -
302 name: "default_name_9 (source firewall.address.name firewall.addrgrp.name)"
303 end_port: "65535"
304 end_source_port: "65535"
305 gateway: "<your_own_value>"
306 groups:
307 -
308 name: "default_name_14 (source user.group.name)"
309 input_device:
310 -
311 name: "default_name_16 (source system.interface.name)"
312 input_device_negate: "enable"
313 internet_service_custom:
314 -
315 name: "default_name_19 (source firewall.internet-service-custom.name)"
316 internet_service_fortiguard:
317 -
318 name: "default_name_21 (source firewall.internet-service-fortiguard.name)"
319 internet_service_id:
320 -
321 id: "23 (source firewall.internet-service.id)"
322 output_device: "<your_own_value> (source system.interface.name)"
323 protocol: "0"
324 seq_num: "<you_own_value>"
325 src:
326 -
327 subnet: "<your_own_value>"
328 src_negate: "enable"
329 srcaddr:
330 -
331 name: "default_name_31 (source firewall.address.name firewall.addrgrp.name)"
332 start_port: "0"
333 start_source_port: "0"
334 status: "enable"
335 tos: "<your_own_value>"
336 tos_mask: "<your_own_value>"
337 users:
338 -
339 name: "default_name_38 (source user.local.name)"
340 """
341
342 RETURN = """
343 build:
344 description: Build number of the fortigate image
345 returned: always
346 type: str
347 sample: '1547'
348 http_method:
349 description: Last method used to provision the content into FortiGate
350 returned: always
351 type: str
352 sample: 'PUT'
353 http_status:
354 description: Last result given by FortiGate on last operation applied
355 returned: always
356 type: str
357 sample: "200"
358 mkey:
359 description: Master key (id) used in the last call to FortiGate
360 returned: success
361 type: str
362 sample: "id"
363 name:
364 description: Name of the table used to fulfill the request
365 returned: always
366 type: str
367 sample: "urlfilter"
368 path:
369 description: Path of the table used to fulfill the request
370 returned: always
371 type: str
372 sample: "webfilter"
373 revision:
374 description: Internal revision number
375 returned: always
376 type: str
377 sample: "17.0.2.10658"
378 serial:
379 description: Serial number of the unit
380 returned: always
381 type: str
382 sample: "FGVMEVYYQT3AB5352"
383 status:
384 description: Indication of the operation's result
385 returned: always
386 type: str
387 sample: "success"
388 vdom:
389 description: Virtual domain used
390 returned: always
391 type: str
392 sample: "root"
393 version:
394 description: Version of the FortiGate
395 returned: always
396 type: str
397 sample: "v5.6.3"
398 """
399 from ansible.module_utils.basic import AnsibleModule
400 from ansible.module_utils.connection import Connection
401 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
402 FortiOSHandler,
403 )
404 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
405 check_legacy_fortiosapi,
406 )
407 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
408 schema_to_module_spec,
409 )
410 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
411 check_schema_versioning,
412 )
413 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
414 FAIL_SOCKET_MSG,
415 )
416 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
417 remove_invalid_fields,
418 )
419 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
420 is_same_comparison,
421 )
422 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
423 serialize,
424 )
425 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
426 find_current_values,
427 )
428 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
429 unify_data_format,
430 )
431
432
433 def filter_router_policy_data(json):
434 option_list = [
435 "action",
436 "comments",
437 "dst",
438 "dst_negate",
439 "dstaddr",
440 "end_port",
441 "end_source_port",
442 "gateway",
443 "groups",
444 "input_device",
445 "input_device_negate",
446 "internet_service_custom",
447 "internet_service_fortiguard",
448 "internet_service_id",
449 "output_device",
450 "protocol",
451 "seq_num",
452 "src",
453 "src_negate",
454 "srcaddr",
455 "start_port",
456 "start_source_port",
457 "status",
458 "tos",
459 "tos_mask",
460 "users",
461 ]
462
463 json = remove_invalid_fields(json)
464 dictionary = {}
465
466 for attribute in option_list:
467 if attribute in json and json[attribute] is not None:
468 dictionary[attribute] = json[attribute]
469
470 return dictionary
471
472
473 def underscore_to_hyphen(data):
474 new_data = None
475 if isinstance(data, list):
476 new_data = []
477 for i, elem in enumerate(data):
478 new_data.append(underscore_to_hyphen(elem))
479 elif isinstance(data, dict):
480 new_data = {}
481 for k, v in data.items():
482 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
483 else:
484 return data
485 return new_data
486
487
488 def router_policy(data, fos, check_mode=False):
489
490 state = None
491 vdom = data["vdom"]
492 parameters = None
493 state = data.get("state", None)
494 router_policy_data = data["router_policy"]
495
496 filtered_data = filter_router_policy_data(router_policy_data)
497 converted_data = underscore_to_hyphen(filtered_data)
498
499 # check_mode starts from here
500 if check_mode:
501 diff = {
502 "before": "",
503 "after": filtered_data,
504 }
505 mkeyname = fos.get_mkeyname(None, None)
506 mkey = fos.get_mkey("router", "policy", filtered_data, vdom=vdom)
507 current_data = fos.get(
508 "router", "policy", vdom=vdom, mkey=mkey, parameters=parameters
509 )
510 is_existed = (
511 current_data
512 and current_data.get("http_status") == 200
513 and (
514 mkeyname
515 and isinstance(current_data.get("results"), list)
516 and len(current_data["results"]) > 0
517 or not mkeyname
518 and current_data["results"] # global object response
519 )
520 )
521
522 # 2. if it exists and the state is 'present' then compare current settings with desired
523 if state == "present" or state is True or state is None:
524 # for non global modules, mkeyname must exist and it's a new module when mkey is None
525 if mkeyname is not None and mkey is None:
526 return False, True, filtered_data, diff
527
528 # if mkey exists then compare each other
529 # record exits and they're matched or not
530 copied_filtered_data = filtered_data.copy()
531 copied_filtered_data.pop(mkeyname, None)
532 unified_filtered_data = unify_data_format(copied_filtered_data)
533
534 current_data_results = current_data.get("results", {})
535 current_config = (
536 current_data_results[0]
537 if mkeyname
538 and isinstance(current_data_results, list)
539 and len(current_data_results) > 0
540 else current_data_results
541 )
542 if is_existed:
543 unified_current_values = find_current_values(
544 unified_filtered_data,
545 unify_data_format(current_config),
546 )
547
548 is_same = is_same_comparison(
549 serialize(unified_current_values), serialize(unified_filtered_data)
550 )
551
552 return (
553 False,
554 not is_same,
555 filtered_data,
556 {"before": unified_current_values, "after": unified_filtered_data},
557 )
558
559 # record does not exist
560 return False, True, filtered_data, diff
561
562 if state == "absent":
563 if mkey is None:
564 return (
565 False,
566 False,
567 filtered_data,
568 {"before": current_data["results"][0], "after": ""},
569 )
570
571 if is_existed:
572 return (
573 False,
574 True,
575 filtered_data,
576 {"before": current_data["results"][0], "after": ""},
577 )
578 return False, False, filtered_data, {}
579
580 return True, False, {"reason: ": "Must provide state parameter"}, {}
581 # pass post processed data to member operations
582 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
583 data_copy = data.copy()
584 data_copy["router_policy"] = filtered_data
585 fos.do_member_operation(
586 "router",
587 "policy",
588 data_copy,
589 )
590
591 if state == "present" or state is True:
592 return fos.set(
593 "router", "policy", data=converted_data, vdom=vdom, parameters=parameters
594 )
595
596 elif state == "absent":
597 return fos.delete(
598 "router",
599 "policy",
600 mkey=converted_data["seq-num"],
601 vdom=vdom,
602 parameters=parameters,
603 )
604 else:
605 fos._module.fail_json(msg="state must be present or absent!")
606
607
608 def is_successful_status(resp):
609 return (
610 "status" in resp
611 and resp["status"] == "success"
612 or "http_status" in resp
613 and resp["http_status"] == 200
614 or "http_method" in resp
615 and resp["http_method"] == "DELETE"
616 and resp["http_status"] == 404
617 )
618
619
620 def fortios_router(data, fos, check_mode):
621
622 if data["router_policy"]:
623 resp = router_policy(data, fos, check_mode)
624 else:
625 fos._module.fail_json(msg="missing task body: %s" % ("router_policy"))
626 if isinstance(resp, tuple) and len(resp) == 4:
627 return resp
628 return (
629 not is_successful_status(resp),
630 is_successful_status(resp)
631 and (resp["revision_changed"] if "revision_changed" in resp else True),
632 resp,
633 {},
634 )
635
636
637 versioned_schema = {
638 "type": "list",
639 "elements": "dict",
640 "children": {
641 "seq_num": {"v_range": [["v6.0.0", ""]], "type": "integer", "required": True},
642 "input_device": {
643 "type": "list",
644 "elements": "dict",
645 "children": {
646 "name": {
647 "v_range": [["v6.0.0", ""]],
648 "type": "string",
649 "required": True,
650 }
651 },
652 "v_range": [["v6.0.0", ""]],
653 },
654 "input_device_negate": {
655 "v_range": [["v6.2.0", ""]],
656 "type": "string",
657 "options": [{"value": "enable"}, {"value": "disable"}],
658 },
659 "src": {
660 "type": "list",
661 "elements": "dict",
662 "children": {
663 "subnet": {
664 "v_range": [["v6.0.0", ""]],
665 "type": "string",
666 "required": True,
667 }
668 },
669 "v_range": [["v6.0.0", ""]],
670 },
671 "srcaddr": {
672 "type": "list",
673 "elements": "dict",
674 "children": {
675 "name": {
676 "v_range": [["v6.0.0", ""]],
677 "type": "string",
678 "required": True,
679 }
680 },
681 "v_range": [["v6.0.0", ""]],
682 },
683 "src_negate": {
684 "v_range": [["v6.0.0", ""]],
685 "type": "string",
686 "options": [{"value": "enable"}, {"value": "disable"}],
687 },
688 "dst": {
689 "type": "list",
690 "elements": "dict",
691 "children": {
692 "subnet": {
693 "v_range": [["v6.0.0", ""]],
694 "type": "string",
695 "required": True,
696 }
697 },
698 "v_range": [["v6.0.0", ""]],
699 },
700 "dstaddr": {
701 "type": "list",
702 "elements": "dict",
703 "children": {
704 "name": {
705 "v_range": [["v6.0.0", ""]],
706 "type": "string",
707 "required": True,
708 }
709 },
710 "v_range": [["v6.0.0", ""]],
711 },
712 "dst_negate": {
713 "v_range": [["v6.0.0", ""]],
714 "type": "string",
715 "options": [{"value": "enable"}, {"value": "disable"}],
716 },
717 "action": {
718 "v_range": [["v6.0.0", ""]],
719 "type": "string",
720 "options": [{"value": "deny"}, {"value": "permit"}],
721 },
722 "protocol": {"v_range": [["v6.0.0", ""]], "type": "integer"},
723 "start_port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
724 "end_port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
725 "start_source_port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
726 "end_source_port": {"v_range": [["v6.0.0", ""]], "type": "integer"},
727 "gateway": {"v_range": [["v6.0.0", ""]], "type": "string"},
728 "output_device": {"v_range": [["v6.0.0", ""]], "type": "string"},
729 "tos": {"v_range": [["v6.0.0", ""]], "type": "string"},
730 "tos_mask": {"v_range": [["v6.0.0", ""]], "type": "string"},
731 "status": {
732 "v_range": [["v6.0.0", ""]],
733 "type": "string",
734 "options": [{"value": "enable"}, {"value": "disable"}],
735 },
736 "comments": {"v_range": [["v6.0.0", ""]], "type": "string"},
737 "internet_service_id": {
738 "type": "list",
739 "elements": "dict",
740 "children": {
741 "id": {"v_range": [["v6.2.0", ""]], "type": "integer", "required": True}
742 },
743 "v_range": [["v6.2.0", ""]],
744 },
745 "internet_service_custom": {
746 "type": "list",
747 "elements": "dict",
748 "children": {
749 "name": {
750 "v_range": [["v6.2.0", ""]],
751 "type": "string",
752 "required": True,
753 }
754 },
755 "v_range": [["v6.2.0", ""]],
756 },
757 "internet_service_fortiguard": {
758 "type": "list",
759 "elements": "dict",
760 "children": {
761 "name": {
762 "v_range": [["v7.6.4", ""]],
763 "type": "string",
764 "required": True,
765 }
766 },
767 "v_range": [["v7.6.4", ""]],
768 },
769 "users": {
770 "type": "list",
771 "elements": "dict",
772 "children": {
773 "name": {
774 "v_range": [["v7.6.3", ""]],
775 "type": "string",
776 "required": True,
777 }
778 },
779 "v_range": [["v7.6.3", ""]],
780 },
781 "groups": {
782 "type": "list",
783 "elements": "dict",
784 "children": {
785 "name": {
786 "v_range": [["v7.6.3", ""]],
787 "type": "string",
788 "required": True,
789 }
790 },
791 "v_range": [["v7.6.3", ""]],
792 },
793 },
794 "v_range": [["v6.0.0", ""]],
795 }
796
797
798 def main():
799 module_spec = schema_to_module_spec(versioned_schema)
800 mkeyname = "seq_num"
801 fields = {
802 "access_token": {"required": False, "type": "str", "no_log": True},
803 "enable_log": {"required": False, "type": "bool", "default": False},
804 "vdom": {"required": False, "type": "str", "default": "root"},
805 "member_path": {"required": False, "type": "str"},
806 "member_state": {
807 "type": "str",
808 "required": False,
809 "choices": ["present", "absent"],
810 },
811 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
812 "router_policy": {
813 "required": False,
814 "type": "dict",
815 "default": None,
816 "options": {},
817 },
818 }
819 for attribute_name in module_spec["options"]:
820 fields["router_policy"]["options"][attribute_name] = module_spec["options"][
821 attribute_name
822 ]
823 if mkeyname and mkeyname == attribute_name:
824 fields["router_policy"]["options"][attribute_name]["required"] = True
825
826 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
827 check_legacy_fortiosapi(module)
828
829 is_error = False
830 has_changed = False
831 result = None
832 diff = None
833
834 versions_check_result = None
835 if module._socket_path:
836 connection = Connection(module._socket_path)
837 if "access_token" in module.params:
838 connection.set_custom_option("access_token", module.params["access_token"])
839
840 if "enable_log" in module.params:
841 connection.set_custom_option("enable_log", module.params["enable_log"])
842 else:
843 connection.set_custom_option("enable_log", False)
844 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
845 versions_check_result = check_schema_versioning(
846 fos, versioned_schema, "router_policy"
847 )
848
849 is_error, has_changed, result, diff = fortios_router(
850 module.params, fos, module.check_mode
851 )
852
853 else:
854 module.fail_json(**FAIL_SOCKET_MSG)
855
856 if versions_check_result and versions_check_result["matched"] is False:
857 module.warn(
858 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
859 )
860
861 if not is_error:
862 if versions_check_result and versions_check_result["matched"] is False:
863 module.exit_json(
864 changed=has_changed,
865 version_check_warning=versions_check_result,
866 meta=result,
867 diff=diff,
868 )
869 else:
870 module.exit_json(changed=has_changed, meta=result, diff=diff)
871 else:
872 if versions_check_result and versions_check_result["matched"] is False:
873 module.fail_json(
874 msg="Error in repo",
875 version_check_warning=versions_check_result,
876 meta=result,
877 )
878 else:
879 module.fail_json(msg="Error in repo", meta=result)
880
881
882 if __name__ == "__main__":
883 main()