Debian Codegraph @

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