Debian Codegraph @

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