Debian Codegraph @

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