Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_firewall_ippool.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_ippool
23 short_description: Configure IPv4 IP pools 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 ippool 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_ippool:
88 description:
89 - Configure IPv4 IP pools.
90 default: null
91 type: dict
92 suboptions:
93 add_nat64_route:
94 description:
95 - Enable/disable adding NAT64 route.
96 type: str
97 choices:
98 - 'disable'
99 - 'enable'
100 arp_intf:
101 description:
102 - Select an interface from available options that will reply to ARP requests. (If blank, any is selected). Source system.interface.name.
103 type: str
104 arp_reply:
105 description:
106 - Enable/disable replying to ARP requests when an IP Pool is added to a policy .
107 type: str
108 choices:
109 - 'disable'
110 - 'enable'
111 associated_interface:
112 description:
113 - Associated interface name. Source system.interface.name.
114 type: str
115 block_size:
116 description:
117 - Number of addresses in a block (64 - 4096).
118 type: int
119 client_prefix_length:
120 description:
121 - Subnet length of a single deterministic NAT64 client (1 - 128).
122 type: int
123 comments:
124 description:
125 - Comment.
126 type: str
127 endip:
128 description:
129 - 'Final IPv4 address (inclusive) in the range for the address pool (format xxx.xxx.xxx.xxx).'
130 type: str
131 endport:
132 description:
133 - 'Final port number (inclusive) in the range for the address pool (1024 - 65535).'
134 type: int
135 icmp_session_quota:
136 description:
137 - Maximum number of concurrent ICMP sessions allowed per client (0 - 2097000).
138 type: int
139 name:
140 description:
141 - IP pool name.
142 required: true
143 type: str
144 nat64:
145 description:
146 - Enable/disable NAT64.
147 type: str
148 choices:
149 - 'disable'
150 - 'enable'
151 num_blocks_per_user:
152 description:
153 - Number of addresses blocks that can be used by a user (1 to 128).
154 type: int
155 pba_interim_log:
156 description:
157 - Port block allocation interim logging interval (600 - 86400 seconds).
158 type: int
159 pba_timeout:
160 description:
161 - Port block allocation timeout (seconds).
162 type: int
163 permit_any_host:
164 description:
165 - Enable/disable fullcone NAT. Accept UDP packets from any host.
166 type: str
167 choices:
168 - 'disable'
169 - 'enable'
170 port_per_user:
171 description:
172 - Number of port for each user (32 - 60416).
173 type: int
174 privileged_port_use_pba:
175 description:
176 - Enable/disable selection of the external port from the port block allocation for NAT"ing privileged ports (deafult = disable).
177 type: str
178 choices:
179 - 'disable'
180 - 'enable'
181 source_endip:
182 description:
183 - 'Final IPv4 address (inclusive) in the range of the source addresses to be translated (format xxx.xxx.xxx.xxx).'
184 type: str
185 source_prefix6:
186 description:
187 - 'Source IPv6 network to be translated (format = xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/xxx).'
188 type: str
189 source_startip:
190 description:
191 - First IPv4 address (inclusive) in the range of the source addresses to be translated (format = xxx.xxx.xxx.xxx).
192 type: str
193 startip:
194 description:
195 - 'First IPv4 address (inclusive) in the range for the address pool (format xxx.xxx.xxx.xxx).'
196 type: str
197 startport:
198 description:
199 - 'First port number (inclusive) in the range for the address pool (1024 - 65535).'
200 type: int
201 subnet_broadcast_in_ippool:
202 description:
203 - Enable/disable inclusion of the subnetwork address and broadcast IP address in the NAT64 IP pool.
204 type: str
205 choices:
206 - 'disable'
207 - 'enable'
208 tcp_session_quota:
209 description:
210 - Maximum number of concurrent TCP sessions allowed per client (0 - 2097000).
211 type: int
212 type:
213 description:
214 - 'IP pool type: overload, one-to-one, fixed-port-range, port-block-allocation, cgn-resource-allocation (hyperscale vdom only)'
215 type: str
216 choices:
217 - 'overload'
218 - 'one-to-one'
219 - 'fixed-port-range'
220 - 'port-block-allocation'
221 udp_session_quota:
222 description:
223 - Maximum number of concurrent UDP sessions allowed per client (0 - 2097000).
224 type: int
225 """
226
227 EXAMPLES = """
228 - name: Configure IPv4 IP pools.
229 fortinet.fortios.fortios_firewall_ippool:
230 vdom: "{{ vdom }}"
231 state: "present"
232 access_token: "<your_own_value>"
233 firewall_ippool:
234 add_nat64_route: "disable"
235 arp_intf: "<your_own_value> (source system.interface.name)"
236 arp_reply: "disable"
237 associated_interface: "<your_own_value> (source system.interface.name)"
238 block_size: "128"
239 client_prefix_length: "64"
240 comments: "<your_own_value>"
241 endip: "<your_own_value>"
242 endport: "65533"
243 icmp_session_quota: "0"
244 name: "default_name_13"
245 nat64: "disable"
246 num_blocks_per_user: "8"
247 pba_interim_log: "0"
248 pba_timeout: "30"
249 permit_any_host: "disable"
250 port_per_user: "0"
251 privileged_port_use_pba: "disable"
252 source_endip: "<your_own_value>"
253 source_prefix6: "<your_own_value>"
254 source_startip: "<your_own_value>"
255 startip: "<your_own_value>"
256 startport: "5117"
257 subnet_broadcast_in_ippool: "disable"
258 tcp_session_quota: "0"
259 type: "overload"
260 udp_session_quota: "0"
261 """
262
263 RETURN = """
264 build:
265 description: Build number of the fortigate image
266 returned: always
267 type: str
268 sample: '1547'
269 http_method:
270 description: Last method used to provision the content into FortiGate
271 returned: always
272 type: str
273 sample: 'PUT'
274 http_status:
275 description: Last result given by FortiGate on last operation applied
276 returned: always
277 type: str
278 sample: "200"
279 mkey:
280 description: Master key (id) used in the last call to FortiGate
281 returned: success
282 type: str
283 sample: "id"
284 name:
285 description: Name of the table used to fulfill the request
286 returned: always
287 type: str
288 sample: "urlfilter"
289 path:
290 description: Path of the table used to fulfill the request
291 returned: always
292 type: str
293 sample: "webfilter"
294 revision:
295 description: Internal revision number
296 returned: always
297 type: str
298 sample: "17.0.2.10658"
299 serial:
300 description: Serial number of the unit
301 returned: always
302 type: str
303 sample: "FGVMEVYYQT3AB5352"
304 status:
305 description: Indication of the operation's result
306 returned: always
307 type: str
308 sample: "success"
309 vdom:
310 description: Virtual domain used
311 returned: always
312 type: str
313 sample: "root"
314 version:
315 description: Version of the FortiGate
316 returned: always
317 type: str
318 sample: "v5.6.3"
319 """
320 from ansible.module_utils.basic import AnsibleModule
321 from ansible.module_utils.connection import Connection
322 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
323 FortiOSHandler,
324 )
325 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
326 check_legacy_fortiosapi,
327 )
328 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
329 schema_to_module_spec,
330 )
331 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
332 check_schema_versioning,
333 )
334 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
335 FAIL_SOCKET_MSG,
336 )
337 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
338 remove_invalid_fields,
339 )
340 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
341 is_same_comparison,
342 )
343 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
344 serialize,
345 )
346 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
347 find_current_values,
348 )
349 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
350 unify_data_format,
351 )
352
353
354 def filter_firewall_ippool_data(json):
355 option_list = [
356 "add_nat64_route",
357 "arp_intf",
358 "arp_reply",
359 "associated_interface",
360 "block_size",
361 "client_prefix_length",
362 "comments",
363 "endip",
364 "endport",
365 "icmp_session_quota",
366 "name",
367 "nat64",
368 "num_blocks_per_user",
369 "pba_interim_log",
370 "pba_timeout",
371 "permit_any_host",
372 "port_per_user",
373 "privileged_port_use_pba",
374 "source_endip",
375 "source_prefix6",
376 "source_startip",
377 "startip",
378 "startport",
379 "subnet_broadcast_in_ippool",
380 "tcp_session_quota",
381 "type",
382 "udp_session_quota",
383 ]
384
385 json = remove_invalid_fields(json)
386 dictionary = {}
387
388 for attribute in option_list:
389 if attribute in json and json[attribute] is not None:
390 dictionary[attribute] = json[attribute]
391
392 return dictionary
393
394
395 def underscore_to_hyphen(data):
396 new_data = None
397 if isinstance(data, list):
398 new_data = []
399 for i, elem in enumerate(data):
400 new_data.append(underscore_to_hyphen(elem))
401 elif isinstance(data, dict):
402 new_data = {}
403 for k, v in data.items():
404 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
405 else:
406 return data
407 return new_data
408
409
410 def firewall_ippool(data, fos, check_mode=False):
411
412 state = None
413 vdom = data["vdom"]
414 parameters = None
415 state = data.get("state", None)
416 firewall_ippool_data = data["firewall_ippool"]
417
418 filtered_data = filter_firewall_ippool_data(firewall_ippool_data)
419 converted_data = underscore_to_hyphen(filtered_data)
420
421 # check_mode starts from here
422 if check_mode:
423 diff = {
424 "before": "",
425 "after": filtered_data,
426 }
427 mkeyname = fos.get_mkeyname(None, None)
428 mkey = fos.get_mkey("firewall", "ippool", filtered_data, vdom=vdom)
429 current_data = fos.get(
430 "firewall", "ippool", vdom=vdom, mkey=mkey, parameters=parameters
431 )
432 is_existed = (
433 current_data
434 and current_data.get("http_status") == 200
435 and (
436 mkeyname
437 and isinstance(current_data.get("results"), list)
438 and len(current_data["results"]) > 0
439 or not mkeyname
440 and current_data["results"] # global object response
441 )
442 )
443
444 # 2. if it exists and the state is 'present' then compare current settings with desired
445 if state == "present" or state is True or state is None:
446 # for non global modules, mkeyname must exist and it's a new module when mkey is None
447 if mkeyname is not None and mkey is None:
448 return False, True, filtered_data, diff
449
450 # if mkey exists then compare each other
451 # record exits and they're matched or not
452 copied_filtered_data = filtered_data.copy()
453 copied_filtered_data.pop(mkeyname, None)
454 unified_filtered_data = unify_data_format(copied_filtered_data)
455
456 current_data_results = current_data.get("results", {})
457 current_config = (
458 current_data_results[0]
459 if mkeyname
460 and isinstance(current_data_results, list)
461 and len(current_data_results) > 0
462 else current_data_results
463 )
464 if is_existed:
465 unified_current_values = find_current_values(
466 unified_filtered_data,
467 unify_data_format(current_config),
468 )
469
470 is_same = is_same_comparison(
471 serialize(unified_current_values), serialize(unified_filtered_data)
472 )
473
474 return (
475 False,
476 not is_same,
477 filtered_data,
478 {"before": unified_current_values, "after": unified_filtered_data},
479 )
480
481 # record does not exist
482 return False, True, filtered_data, diff
483
484 if state == "absent":
485 if mkey is None:
486 return (
487 False,
488 False,
489 filtered_data,
490 {"before": current_data["results"][0], "after": ""},
491 )
492
493 if is_existed:
494 return (
495 False,
496 True,
497 filtered_data,
498 {"before": current_data["results"][0], "after": ""},
499 )
500 return False, False, filtered_data, {}
501
502 return True, False, {"reason: ": "Must provide state parameter"}, {}
503 # pass post processed data to member operations
504 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
505 data_copy = data.copy()
506 data_copy["firewall_ippool"] = filtered_data
507 fos.do_member_operation(
508 "firewall",
509 "ippool",
510 data_copy,
511 )
512
513 if state == "present" or state is True:
514 return fos.set(
515 "firewall", "ippool", data=converted_data, vdom=vdom, parameters=parameters
516 )
517
518 elif state == "absent":
519 return fos.delete(
520 "firewall",
521 "ippool",
522 mkey=converted_data["name"],
523 vdom=vdom,
524 parameters=parameters,
525 )
526 else:
527 fos._module.fail_json(msg="state must be present or absent!")
528
529
530 def is_successful_status(resp):
531 return (
532 "status" in resp
533 and resp["status"] == "success"
534 or "http_status" in resp
535 and resp["http_status"] == 200
536 or "http_method" in resp
537 and resp["http_method"] == "DELETE"
538 and resp["http_status"] == 404
539 )
540
541
542 def fortios_firewall(data, fos, check_mode):
543
544 if data["firewall_ippool"]:
545 resp = firewall_ippool(data, fos, check_mode)
546 else:
547 fos._module.fail_json(msg="missing task body: %s" % ("firewall_ippool"))
548 if isinstance(resp, tuple) and len(resp) == 4:
549 return resp
550 return (
551 not is_successful_status(resp),
552 is_successful_status(resp)
553 and (resp["revision_changed"] if "revision_changed" in resp else True),
554 resp,
555 {},
556 )
557
558
559 versioned_schema = {
560 "type": "list",
561 "elements": "dict",
562 "children": {
563 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
564 "type": {
565 "v_range": [["v6.0.0", ""]],
566 "type": "string",
567 "options": [
568 {"value": "overload"},
569 {"value": "one-to-one"},
570 {"value": "fixed-port-range"},
571 {"value": "port-block-allocation"},
572 ],
573 },
574 "startip": {"v_range": [["v6.0.0", ""]], "type": "string"},
575 "endip": {"v_range": [["v6.0.0", ""]], "type": "string"},
576 "startport": {"v_range": [["v7.0.0", ""]], "type": "integer"},
577 "endport": {"v_range": [["v7.0.0", ""]], "type": "integer"},
578 "source_startip": {"v_range": [["v6.0.0", ""]], "type": "string"},
579 "source_endip": {"v_range": [["v6.0.0", ""]], "type": "string"},
580 "block_size": {"v_range": [["v6.0.0", ""]], "type": "integer"},
581 "port_per_user": {"v_range": [["v7.0.0", ""]], "type": "integer"},
582 "num_blocks_per_user": {"v_range": [["v6.0.0", ""]], "type": "integer"},
583 "pba_timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
584 "pba_interim_log": {"v_range": [["v7.4.4", ""]], "type": "integer"},
585 "permit_any_host": {
586 "v_range": [["v6.0.0", ""]],
587 "type": "string",
588 "options": [{"value": "disable"}, {"value": "enable"}],
589 },
590 "arp_reply": {
591 "v_range": [["v6.0.0", ""]],
592 "type": "string",
593 "options": [{"value": "disable"}, {"value": "enable"}],
594 },
595 "arp_intf": {"v_range": [["v6.0.0", ""]], "type": "string"},
596 "associated_interface": {"v_range": [["v6.0.0", ""]], "type": "string"},
597 "comments": {"v_range": [["v6.0.0", ""]], "type": "string"},
598 "nat64": {
599 "v_range": [["v7.0.1", ""]],
600 "type": "string",
601 "options": [{"value": "disable"}, {"value": "enable"}],
602 },
603 "add_nat64_route": {
604 "v_range": [["v7.0.1", ""]],
605 "type": "string",
606 "options": [{"value": "disable"}, {"value": "enable"}],
607 },
608 "source_prefix6": {"v_range": [["v7.6.0", ""]], "type": "string"},
609 "client_prefix_length": {"v_range": [["v7.6.0", ""]], "type": "integer"},
610 "tcp_session_quota": {"v_range": [["v7.6.0", ""]], "type": "integer"},
611 "udp_session_quota": {"v_range": [["v7.6.0", ""]], "type": "integer"},
612 "icmp_session_quota": {"v_range": [["v7.6.0", ""]], "type": "integer"},
613 "privileged_port_use_pba": {
614 "v_range": [["v7.6.0", ""]],
615 "type": "string",
616 "options": [{"value": "disable"}, {"value": "enable"}],
617 },
618 "subnet_broadcast_in_ippool": {
619 "v_range": [["v7.0.8", "v7.0.12"], ["v7.2.4", ""]],
620 "type": "string",
621 "options": [
622 {"value": "disable"},
623 {
624 "value": "enable",
625 "v_range": [["v7.0.8", "v7.0.12"], ["v7.2.4", "v7.4.4"]],
626 },
627 ],
628 },
629 },
630 "v_range": [["v6.0.0", ""]],
631 }
632
633
634 def main():
635 module_spec = schema_to_module_spec(versioned_schema)
636 mkeyname = "name"
637 fields = {
638 "access_token": {"required": False, "type": "str", "no_log": True},
639 "enable_log": {"required": False, "type": "bool", "default": False},
640 "vdom": {"required": False, "type": "str", "default": "root"},
641 "member_path": {"required": False, "type": "str"},
642 "member_state": {
643 "type": "str",
644 "required": False,
645 "choices": ["present", "absent"],
646 },
647 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
648 "firewall_ippool": {
649 "required": False,
650 "type": "dict",
651 "default": None,
652 "options": {},
653 },
654 }
655 for attribute_name in module_spec["options"]:
656 fields["firewall_ippool"]["options"][attribute_name] = module_spec["options"][
657 attribute_name
658 ]
659 if mkeyname and mkeyname == attribute_name:
660 fields["firewall_ippool"]["options"][attribute_name]["required"] = True
661
662 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
663 check_legacy_fortiosapi(module)
664
665 is_error = False
666 has_changed = False
667 result = None
668 diff = None
669
670 versions_check_result = None
671 if module._socket_path:
672 connection = Connection(module._socket_path)
673 if "access_token" in module.params:
674 connection.set_custom_option("access_token", module.params["access_token"])
675
676 if "enable_log" in module.params:
677 connection.set_custom_option("enable_log", module.params["enable_log"])
678 else:
679 connection.set_custom_option("enable_log", False)
680 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
681 versions_check_result = check_schema_versioning(
682 fos, versioned_schema, "firewall_ippool"
683 )
684
685 is_error, has_changed, result, diff = fortios_firewall(
686 module.params, fos, module.check_mode
687 )
688
689 else:
690 module.fail_json(**FAIL_SOCKET_MSG)
691
692 if versions_check_result and versions_check_result["matched"] is False:
693 module.warn(
694 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
695 )
696
697 if not is_error:
698 if versions_check_result and versions_check_result["matched"] is False:
699 module.exit_json(
700 changed=has_changed,
701 version_check_warning=versions_check_result,
702 meta=result,
703 diff=diff,
704 )
705 else:
706 module.exit_json(changed=has_changed, meta=result, diff=diff)
707 else:
708 if versions_check_result and versions_check_result["matched"] is False:
709 module.fail_json(
710 msg="Error in repo",
711 version_check_warning=versions_check_result,
712 meta=result,
713 )
714 else:
715 module.fail_json(msg="Error in repo", meta=result)
716
717
718 if __name__ == "__main__":
719 main()