Debian Codegraph @

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