Debian Codegraph @

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