Debian Codegraph @

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