Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_firewall_ippool6.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_ippool6
23 short_description: Configure IPv6 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 ippool6 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_ippool6:
88 description:
89 - Configure IPv6 IP pools.
90 default: null
91 type: dict
92 suboptions:
93 add_nat46_route:
94 description:
95 - Enable/disable adding NAT46 route.
96 type: str
97 choices:
98 - 'disable'
99 - 'enable'
100 comments:
101 description:
102 - Comment.
103 type: str
104 endip:
105 description:
106 - 'Final IPv6 address (inclusive) in the range for the address pool (format = xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx).'
107 type: str
108 external_prefix:
109 description:
110 - External NPTv6 prefix length (32 - 64).
111 type: str
112 internal_prefix:
113 description:
114 - Internal NPTv6 prefix length (32 - 64).
115 type: str
116 name:
117 description:
118 - IPv6 IP pool name.
119 required: true
120 type: str
121 nat46:
122 description:
123 - Enable/disable NAT46.
124 type: str
125 choices:
126 - 'disable'
127 - 'enable'
128 startip:
129 description:
130 - 'First IPv6 address (inclusive) in the range for the address pool (format = xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx).'
131 type: str
132 type:
133 description:
134 - Configure IPv6 pool type (overload or NPTv6).
135 type: str
136 choices:
137 - 'overload'
138 - 'nptv6'
139 """
140
141 EXAMPLES = """
142 - name: Configure IPv6 IP pools.
143 fortinet.fortios.fortios_firewall_ippool6:
144 vdom: "{{ vdom }}"
145 state: "present"
146 access_token: "<your_own_value>"
147 firewall_ippool6:
148 add_nat46_route: "disable"
149 comments: "<your_own_value>"
150 endip: "<your_own_value>"
151 external_prefix: "<your_own_value>"
152 internal_prefix: "<your_own_value>"
153 name: "default_name_8"
154 nat46: "disable"
155 startip: "<your_own_value>"
156 type: "overload"
157 """
158
159 RETURN = """
160 build:
161 description: Build number of the fortigate image
162 returned: always
163 type: str
164 sample: '1547'
165 http_method:
166 description: Last method used to provision the content into FortiGate
167 returned: always
168 type: str
169 sample: 'PUT'
170 http_status:
171 description: Last result given by FortiGate on last operation applied
172 returned: always
173 type: str
174 sample: "200"
175 mkey:
176 description: Master key (id) used in the last call to FortiGate
177 returned: success
178 type: str
179 sample: "id"
180 name:
181 description: Name of the table used to fulfill the request
182 returned: always
183 type: str
184 sample: "urlfilter"
185 path:
186 description: Path of the table used to fulfill the request
187 returned: always
188 type: str
189 sample: "webfilter"
190 revision:
191 description: Internal revision number
192 returned: always
193 type: str
194 sample: "17.0.2.10658"
195 serial:
196 description: Serial number of the unit
197 returned: always
198 type: str
199 sample: "FGVMEVYYQT3AB5352"
200 status:
201 description: Indication of the operation's result
202 returned: always
203 type: str
204 sample: "success"
205 vdom:
206 description: Virtual domain used
207 returned: always
208 type: str
209 sample: "root"
210 version:
211 description: Version of the FortiGate
212 returned: always
213 type: str
214 sample: "v5.6.3"
215 """
216 from ansible.module_utils.basic import AnsibleModule
217 from ansible.module_utils.connection import Connection
218 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
219 FortiOSHandler,
220 )
221 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
222 check_legacy_fortiosapi,
223 )
224 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
225 schema_to_module_spec,
226 )
227 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
228 check_schema_versioning,
229 )
230 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
231 FAIL_SOCKET_MSG,
232 )
233 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
234 remove_invalid_fields,
235 )
236 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
237 is_same_comparison,
238 )
239 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
240 serialize,
241 )
242 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
243 find_current_values,
244 )
245 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
246 unify_data_format,
247 )
248
249
250 def filter_firewall_ippool6_data(json):
251 option_list = [
252 "add_nat46_route",
253 "comments",
254 "endip",
255 "external_prefix",
256 "internal_prefix",
257 "name",
258 "nat46",
259 "startip",
260 "type",
261 ]
262
263 json = remove_invalid_fields(json)
264 dictionary = {}
265
266 for attribute in option_list:
267 if attribute in json and json[attribute] is not None:
268 dictionary[attribute] = json[attribute]
269
270 return dictionary
271
272
273 def underscore_to_hyphen(data):
274 new_data = None
275 if isinstance(data, list):
276 new_data = []
277 for i, elem in enumerate(data):
278 new_data.append(underscore_to_hyphen(elem))
279 elif isinstance(data, dict):
280 new_data = {}
281 for k, v in data.items():
282 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
283 else:
284 return data
285 return new_data
286
287
288 def firewall_ippool6(data, fos, check_mode=False):
289
290 state = None
291 vdom = data["vdom"]
292 parameters = None
293 state = data.get("state", None)
294 firewall_ippool6_data = data["firewall_ippool6"]
295
296 filtered_data = filter_firewall_ippool6_data(firewall_ippool6_data)
297 converted_data = underscore_to_hyphen(filtered_data)
298
299 # check_mode starts from here
300 if check_mode:
301 diff = {
302 "before": "",
303 "after": filtered_data,
304 }
305 mkeyname = fos.get_mkeyname(None, None)
306 mkey = fos.get_mkey("firewall", "ippool6", filtered_data, vdom=vdom)
307 current_data = fos.get(
308 "firewall", "ippool6", vdom=vdom, mkey=mkey, parameters=parameters
309 )
310 is_existed = (
311 current_data
312 and current_data.get("http_status") == 200
313 and (
314 mkeyname
315 and isinstance(current_data.get("results"), list)
316 and len(current_data["results"]) > 0
317 or not mkeyname
318 and current_data["results"] # global object response
319 )
320 )
321
322 # 2. if it exists and the state is 'present' then compare current settings with desired
323 if state == "present" or state is True or state is None:
324 # for non global modules, mkeyname must exist and it's a new module when mkey is None
325 if mkeyname is not None and mkey is None:
326 return False, True, filtered_data, diff
327
328 # if mkey exists then compare each other
329 # record exits and they're matched or not
330 copied_filtered_data = filtered_data.copy()
331 copied_filtered_data.pop(mkeyname, None)
332 unified_filtered_data = unify_data_format(copied_filtered_data)
333
334 current_data_results = current_data.get("results", {})
335 current_config = (
336 current_data_results[0]
337 if mkeyname
338 and isinstance(current_data_results, list)
339 and len(current_data_results) > 0
340 else current_data_results
341 )
342 if is_existed:
343 unified_current_values = find_current_values(
344 unified_filtered_data,
345 unify_data_format(current_config),
346 )
347
348 is_same = is_same_comparison(
349 serialize(unified_current_values), serialize(unified_filtered_data)
350 )
351
352 return (
353 False,
354 not is_same,
355 filtered_data,
356 {"before": unified_current_values, "after": unified_filtered_data},
357 )
358
359 # record does not exist
360 return False, True, filtered_data, diff
361
362 if state == "absent":
363 if mkey is None:
364 return (
365 False,
366 False,
367 filtered_data,
368 {"before": current_data["results"][0], "after": ""},
369 )
370
371 if is_existed:
372 return (
373 False,
374 True,
375 filtered_data,
376 {"before": current_data["results"][0], "after": ""},
377 )
378 return False, False, filtered_data, {}
379
380 return True, False, {"reason: ": "Must provide state parameter"}, {}
381 # pass post processed data to member operations
382 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
383 data_copy = data.copy()
384 data_copy["firewall_ippool6"] = filtered_data
385 fos.do_member_operation(
386 "firewall",
387 "ippool6",
388 data_copy,
389 )
390
391 if state == "present" or state is True:
392 return fos.set(
393 "firewall", "ippool6", data=converted_data, vdom=vdom, parameters=parameters
394 )
395
396 elif state == "absent":
397 return fos.delete(
398 "firewall",
399 "ippool6",
400 mkey=converted_data["name"],
401 vdom=vdom,
402 parameters=parameters,
403 )
404 else:
405 fos._module.fail_json(msg="state must be present or absent!")
406
407
408 def is_successful_status(resp):
409 return (
410 "status" in resp
411 and resp["status"] == "success"
412 or "http_status" in resp
413 and resp["http_status"] == 200
414 or "http_method" in resp
415 and resp["http_method"] == "DELETE"
416 and resp["http_status"] == 404
417 )
418
419
420 def fortios_firewall(data, fos, check_mode):
421
422 if data["firewall_ippool6"]:
423 resp = firewall_ippool6(data, fos, check_mode)
424 else:
425 fos._module.fail_json(msg="missing task body: %s" % ("firewall_ippool6"))
426 if isinstance(resp, tuple) and len(resp) == 4:
427 return resp
428 return (
429 not is_successful_status(resp),
430 is_successful_status(resp)
431 and (resp["revision_changed"] if "revision_changed" in resp else True),
432 resp,
433 {},
434 )
435
436
437 versioned_schema = {
438 "type": "list",
439 "elements": "dict",
440 "children": {
441 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
442 "type": {
443 "v_range": [["v7.6.0", ""]],
444 "type": "string",
445 "options": [{"value": "overload"}, {"value": "nptv6"}],
446 },
447 "startip": {"v_range": [["v6.0.0", ""]], "type": "string"},
448 "endip": {"v_range": [["v6.0.0", ""]], "type": "string"},
449 "internal_prefix": {"v_range": [["v7.6.0", ""]], "type": "string"},
450 "external_prefix": {"v_range": [["v7.6.0", ""]], "type": "string"},
451 "comments": {"v_range": [["v6.0.0", ""]], "type": "string"},
452 "nat46": {
453 "v_range": [["v7.0.1", ""]],
454 "type": "string",
455 "options": [{"value": "disable"}, {"value": "enable"}],
456 },
457 "add_nat46_route": {
458 "v_range": [["v7.0.1", ""]],
459 "type": "string",
460 "options": [{"value": "disable"}, {"value": "enable"}],
461 },
462 },
463 "v_range": [["v6.0.0", ""]],
464 }
465
466
467 def main():
468 module_spec = schema_to_module_spec(versioned_schema)
469 mkeyname = "name"
470 fields = {
471 "access_token": {"required": False, "type": "str", "no_log": True},
472 "enable_log": {"required": False, "type": "bool", "default": False},
473 "vdom": {"required": False, "type": "str", "default": "root"},
474 "member_path": {"required": False, "type": "str"},
475 "member_state": {
476 "type": "str",
477 "required": False,
478 "choices": ["present", "absent"],
479 },
480 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
481 "firewall_ippool6": {
482 "required": False,
483 "type": "dict",
484 "default": None,
485 "options": {},
486 },
487 }
488 for attribute_name in module_spec["options"]:
489 fields["firewall_ippool6"]["options"][attribute_name] = module_spec["options"][
490 attribute_name
491 ]
492 if mkeyname and mkeyname == attribute_name:
493 fields["firewall_ippool6"]["options"][attribute_name]["required"] = True
494
495 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
496 check_legacy_fortiosapi(module)
497
498 is_error = False
499 has_changed = False
500 result = None
501 diff = None
502
503 versions_check_result = None
504 if module._socket_path:
505 connection = Connection(module._socket_path)
506 if "access_token" in module.params:
507 connection.set_custom_option("access_token", module.params["access_token"])
508
509 if "enable_log" in module.params:
510 connection.set_custom_option("enable_log", module.params["enable_log"])
511 else:
512 connection.set_custom_option("enable_log", False)
513 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
514 versions_check_result = check_schema_versioning(
515 fos, versioned_schema, "firewall_ippool6"
516 )
517
518 is_error, has_changed, result, diff = fortios_firewall(
519 module.params, fos, module.check_mode
520 )
521
522 else:
523 module.fail_json(**FAIL_SOCKET_MSG)
524
525 if versions_check_result and versions_check_result["matched"] is False:
526 module.warn(
527 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
528 )
529
530 if not is_error:
531 if versions_check_result and versions_check_result["matched"] is False:
532 module.exit_json(
533 changed=has_changed,
534 version_check_warning=versions_check_result,
535 meta=result,
536 diff=diff,
537 )
538 else:
539 module.exit_json(changed=has_changed, meta=result, diff=diff)
540 else:
541 if versions_check_result and versions_check_result["matched"] is False:
542 module.fail_json(
543 msg="Error in repo",
544 version_check_warning=versions_check_result,
545 meta=result,
546 )
547 else:
548 module.fail_json(msg="Error in repo", meta=result)
549
550
551 if __name__ == "__main__":
552 main()