Debian Codegraph @

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