Debian Codegraph @

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