Debian Codegraph @

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