Debian Codegraph @

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