Debian Codegraph @

ansible_collections/community/zabbix/plugins/modules/zabbix_correlation.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2024, ONODERA Masaru <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 DOCUMENTATION = """
14 ---
15 module: zabbix_correlation
16
17 short_description: Create/update/delete Zabbix correlation
18
19
20 description:
21 - This module allows you to create, update and delete Zabbix correlation.
22
23 author:
24 - ONODERA Masaru(@masa-orca)
25
26 requirements:
27 - "python >= 3.9"
28
29 version_added: 2.4.0
30
31 options:
32 name:
33 description:
34 - Name of this correlation
35 type: str
36 required: true
37 description:
38 description:
39 - Description of this correlation
40 type: str
41 operations:
42 description:
43 - A operations.
44 type: list
45 elements: dict
46 suboptions:
47 type:
48 description:
49 - Type of the operation.
50 type: str
51 choices:
52 - close_old_events
53 - close_new_event
54 required: true
55 filter:
56 description:
57 - A filter.
58 type: dict
59 suboptions:
60 evaltype:
61 description:
62 - An evaluation method of the filter.
63 type: str
64 choices:
65 - and_or
66 - and
67 - or
68 - custom_expression
69 required: true
70 conditions:
71 description:
72 - A condition.
73 type: list
74 elements: dict
75 required: true
76 suboptions:
77 type:
78 description:
79 - Type of the condition.
80 type: str
81 choices:
82 - old_event_tag
83 - new_event_tag
84 - new_event_host_group
85 - event_tag_pair
86 - old_event_tag_value
87 - new_event_tag_value
88 required: true
89 tag:
90 description:
91 - Event tag (old or new).
92 - This parameter is required if value of I(type) of the condition is C(old_event_tag), C(new_event_tag),
93 C(old_event_tag_value) or C(new_event_tag_value).
94 type: str
95 hostgroup:
96 description:
97 - A name of hostgroup name
98 - This parameter is required if value of I(type) of the condition is C(new_event_host_group).
99 type: str
100 oldtag:
101 description:
102 - Old event tag.
103 - This parameter is required if value of I(type) of the condition is C(event_tag_pair).
104 type: str
105 newtag:
106 description:
107 - New event tag.
108 - This parameter is required if value of I(type) of the condition is C(event_tag_pair).
109 type: str
110 value:
111 description:
112 - Event tag (old or new) value.
113 - This parameter is required if value of I(type) of the condition is C(old_event_tag_value) or C(new_event_tag_value).
114 type: str
115 formulaid:
116 description:
117 - Arbitrary unique ID that is used to reference the condition from a custom expression.
118 - This parameter's value must be only contain capital-case letters.
119 - This parameter is required if value of I(evaltype) of the filter is C(custom_expression).
120 type: str
121 operator:
122 description:
123 - Condition operator.
124 - This parameter is required if value of I(type) of the condition is C(new_event_host_group),
125 C(old_event_tag_value) or C(new_event_tag_value).
126 - You can only select C(equal) or C(not_equal) if value of I(type) of the condition is C(new_event_host_group).
127 type: str
128 choices:
129 - equal
130 - not_equal
131 - like
132 - not_like
133 formula:
134 description:
135 - A custom expression for the filter.
136 - This parameter is required if value of I(evaltype) is C(custom_expression).
137 type: str
138 status:
139 description:
140 - Status of the correlation.
141 choices:
142 - enabled
143 - disabled
144 default: enabled
145 type: str
146 state:
147 description:
148 - State of the correlation.
149 type: str
150 choices:
151 - present
152 - absent
153 default: present
154
155 extends_documentation_fragment:
156 - community.zabbix.zabbix
157
158 """
159
160 EXAMPLES = """
161 # If you want to use Username and Password to be authenticated by Zabbix Server
162 - name: Set credentials to access Zabbix Server API
163 ansible.builtin.set_fact:
164 ansible_user: Admin
165 ansible_httpapi_pass: zabbix
166
167 # If you want to use API token to be authenticated by Zabbix Server
168 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
169 - name: Set API token
170 ansible.builtin.set_fact:
171 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
172
173 - name: Create correlation of 'New event tag correlation'
174 # set task level variables as we change ansible_connection plugin here
175 vars:
176 ansible_network_os: community.zabbix.zabbix
177 ansible_connection: httpapi
178 ansible_httpapi_port: 443
179 ansible_httpapi_use_ssl: true
180 ansible_httpapi_validate_certs: false
181 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
182 ansible_host: zabbix-example-fqdn.org
183 community.zabbix.zabbix_correlation:
184 name: New event tag correlation
185 filter:
186 evaltype: and_or
187 conditions:
188 - type: new_event_tag
189 tag: ok
190 operations:
191 - type: close_old_events
192 """
193
194 RETURN = """
195 msg:
196 description: The result of the operation
197 returned: success
198 type: str
199 sample: 'Successfully created correlation'
200 """
201
202
203 from ansible.module_utils.basic import AnsibleModule
204
205 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
206 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
207
208
209 class Correlation(ZabbixBase):
210 def __init__(self, module, zbx=None, zapi_wrapper=None):
211 super(Correlation, self).__init__(module, zbx, zapi_wrapper)
212
213 def get_correlations(self, correlation_name):
214 try:
215 regexps = self._zapi.correlation.get(
216 {
217 "output": "extend",
218 "selectFilter": "extend",
219 "selectOperations": "extend",
220 "filter": {"name": correlation_name},
221 }
222 )
223 if len(regexps) >= 2:
224 self._module.fail_json("Too many correlations are matched.")
225 return regexps
226 except Exception as e:
227 self._module.fail_json(
228 msg="Failed to get correlation: %s" % e
229 )
230
231 def delete_correlation(self, correlation):
232 try:
233 parameter = [correlation["correlationid"]]
234 if self._module.check_mode:
235 self._module.exit_json(changed=True)
236 self._zapi.correlation.delete(parameter)
237 self._module.exit_json(
238 changed=True, msg="Successfully deleted correlation."
239 )
240 except Exception as e:
241 self._module.fail_json(
242 msg="Failed to delete correlation: %s" % e
243 )
244
245 def _convert_operations_to_json(self, operations):
246 operation_type_values = ["close_old_events", "close_new_event"]
247
248 operations_json = []
249 for operation in operations:
250 operation_json = {}
251 operation_type = zabbix_utils.helper_to_numeric_value(
252 operation_type_values, operation["type"]
253 )
254 operation_json["type"] = str(operation_type)
255 operations_json.append(operation_json)
256
257 return operations_json
258
259 def _get_groupid_from_name(self, hostgroup):
260 groupid = self._zapi.hostgroup.get({"filter": {"name": hostgroup}})
261 if not groupid or len(groupid) > 1:
262 self._module.fail_json("Host group '%s' cannot be found" % hostgroup)
263 return groupid[0]["groupid"]
264
265 def _convert_conditions_to_json(self, filter_parameter):
266 condition_type_values = [
267 "old_event_tag",
268 "new_event_tag",
269 "new_event_host_group",
270 "event_tag_pair",
271 "old_event_tag_value",
272 "new_event_tag_value"
273 ]
274
275 operator_values = [
276 "equal",
277 "not_equal",
278 "like",
279 "not_like"
280 ]
281
282 conditions_json = []
283 for condition in filter_parameter["conditions"]:
284 condition_json = {}
285
286 condition_type = zabbix_utils.helper_to_numeric_value(
287 condition_type_values, condition["type"]
288 )
289 condition_json["type"] = str(condition_type)
290
291 if condition["tag"] is not None:
292 condition_json["tag"] = condition["tag"]
293
294 if condition["hostgroup"] is not None:
295 condition_json["groupid"] = self._get_groupid_from_name(condition["hostgroup"])
296
297 if condition["oldtag"] is not None:
298 condition_json["oldtag"] = condition["oldtag"]
299
300 if condition["newtag"] is not None:
301 condition_json["newtag"] = condition["newtag"]
302
303 if condition["value"] is not None:
304 condition_json["value"] = condition["value"]
305
306 if filter_parameter["evaltype"] == "custom_expression":
307 if condition["formulaid"] is not None:
308 if not condition["formulaid"].isupper():
309 self._module.fail_json(
310 "A value of formulaid must be uppercase."
311 )
312 condition_json["formulaid"] = condition["formulaid"]
313 else:
314 self._module.fail_json(
315 "formulaid must be defined if evaltype is 'custom_expression'."
316 )
317 else:
318 if condition["formulaid"] is not None:
319 self._module.warn(
320 "A value of formulaid will be ignored because evaltype is not 'custom_expression'."
321 )
322
323 if condition["operator"] is not None:
324 if (condition["type"] == "new_event_host_group"
325 and (condition["operator"] == "like" or condition["operator"] == "not_like")):
326 self._module.fail_json(
327 "A value of operator must be equal or not_equal when condition's type is 'new_event_host_group'."
328 )
329 operator = zabbix_utils.helper_to_numeric_value(
330 operator_values, condition["operator"]
331 )
332 condition_json["operator"] = str(operator)
333
334 conditions_json.append(condition_json)
335 return conditions_json
336
337 def _convert_filter_parameter_to_json(self, filter_parameter):
338 evaltype_values = [
339 "and_or",
340 "and",
341 "or",
342 "custom_expression"
343 ]
344
345 filter_parameter_json = {}
346
347 evaltype = zabbix_utils.helper_to_numeric_value(
348 evaltype_values, filter_parameter["evaltype"]
349 )
350 filter_parameter_json["evaltype"] = str(evaltype)
351
352 filter_parameter_json["conditions"] = self._convert_conditions_to_json(filter_parameter)
353
354 if filter_parameter["formula"] is not None:
355 if filter_parameter["evaltype"] == "custom_expression":
356 filter_parameter_json["formula"] = filter_parameter["formula"]
357 else:
358 self._module.warn(
359 "A value of formula will be ignored because evaltype is not 'custom_expression'."
360 )
361
362 return filter_parameter_json
363
364 def create_correlation(self, name, description, operations, filter_parameter, status):
365 status_values = ["enabled", "disabled"]
366 status_json = zabbix_utils.helper_to_numeric_value(
367 status_values, status
368 )
369
370 try:
371 correlation_json = {}
372
373 correlation_json["name"] = name
374
375 if description is not None:
376 correlation_json["description"] = description
377
378 correlation_json["operations"] = self._convert_operations_to_json(operations)
379
380 correlation_json["filter"] = self._convert_filter_parameter_to_json(filter_parameter)
381
382 correlation_json["status"] = status_json
383
384 if self._module.check_mode:
385 self._module.exit_json(changed=True)
386 self._zapi.correlation.create(correlation_json)
387 self._module.exit_json(
388 changed=True, msg="Successfully created correlation"
389 )
390 except Exception as e:
391 self._module.fail_json(
392 msg="Failed to create correlation: %s" % e
393 )
394
395 def check_filter_properties(self, current_filter, future_filter):
396 changed = False
397
398 if (current_filter["evaltype"] != future_filter["evaltype"]):
399 changed = True
400
401 if "formula" in future_filter.keys():
402 if (current_filter["eval_formula"] != future_filter["formula"]):
403 changed = True
404
405 for condition in current_filter["conditions"]:
406 # 3 means custom expression.
407 if current_filter["evaltype"] != "3":
408 condition.pop("formulaid")
409 diff_conditions = []
410 zabbix_utils.helper_compare_lists(current_filter["conditions"], future_filter["conditions"], diff_conditions)
411 if len(diff_conditions) != 0:
412 changed = True
413
414 return changed
415
416 def update_correlation(self, current_correlation, description, operations, filter_parameter, status):
417 status_values = ["enabled", "disabled"]
418 status_json = zabbix_utils.helper_to_numeric_value(
419 status_values, status
420 )
421
422 try:
423 correlation_json = {}
424
425 if description is not None and description != current_correlation["description"]:
426 correlation_json["description"] = description
427
428 if operations is not None:
429 future_operations = self._convert_operations_to_json(operations)
430 diff_operations = []
431 zabbix_utils.helper_compare_lists(current_correlation["operations"], future_operations, diff_operations)
432 if len(diff_operations) != 0:
433 correlation_json["operations"] = future_operations
434
435 if filter_parameter is not None:
436 future_filter = self._convert_filter_parameter_to_json(filter_parameter)
437 if self.check_filter_properties(current_correlation["filter"], future_filter):
438 correlation_json["filter"] = future_filter
439
440 if str(status_json) != current_correlation["status"]:
441 correlation_json["status"] = str(status_json)
442
443 if len(correlation_json.keys()) == 0:
444 self._module.exit_json(changed=False)
445 else:
446 correlation_json["correlationid"] = current_correlation["correlationid"]
447 if self._module.check_mode:
448 self._module.exit_json(changed=True)
449 self._zapi.correlation.update(correlation_json)
450 self._module.exit_json(
451 changed=True, msg="Successfully updated correlation"
452 )
453 except Exception as e:
454 self._module.fail_json(
455 msg="Failed to update correlation: %s" % e
456 )
457
458
459 def main():
460 """Main ansible module function"""
461
462 argument_spec = zabbix_utils.zabbix_common_argument_spec()
463 argument_spec.update(
464 dict(
465 name=dict(type="str", required=True),
466 description=dict(type="str"),
467 operations=dict(
468 type="list",
469 elements="dict",
470 options=dict(
471 type=dict(
472 choices=["close_old_events", "close_new_event"],
473 required=True
474 )
475 )
476 ),
477 filter=dict(
478 type="dict",
479 options=dict(
480 evaltype=dict(
481 type="str",
482 required=True,
483 choices=[
484 "and_or",
485 "and",
486 "or",
487 "custom_expression"
488 ]
489 ),
490 conditions=dict(
491 required=True,
492 type="list",
493 elements="dict",
494 options=dict(
495 type=dict(
496 type="str",
497 required=True,
498 choices=[
499 "old_event_tag",
500 "new_event_tag",
501 "new_event_host_group",
502 "event_tag_pair",
503 "old_event_tag_value",
504 "new_event_tag_value"
505 ]
506 ),
507 tag=dict(type="str"),
508 hostgroup=dict(type="str"),
509 oldtag=dict(type="str"),
510 newtag=dict(type="str"),
511 value=dict(type="str"),
512 formulaid=dict(type="str"),
513 operator=dict(
514 type="str",
515 choices=[
516 "equal",
517 "not_equal",
518 "like",
519 "not_like"
520 ]
521 ),
522 ),
523 required_if=[
524 ["type", "old_event_tag", ["tag"]],
525 ["type", "new_event_tag", ["tag"]],
526 ["type", "new_event_host_group", ["hostgroup", "operator"]],
527 ["type", "event_tag_pair", ["oldtag", "newtag"]],
528 ["type", "old_event_tag_value", ["tag", "value", "operator"]],
529 ["type", "new_event_tag_value", ["tag", "value", "operator"]]
530 ],
531 mutually_exclusive=[
532 ("tag", "hostgroup", "oldtag")
533 ],
534 required_together=[
535 ('oldtag', 'newtag')
536 ]
537 ),
538 formula=dict(type="str"),
539 ),
540 required_if=[
541 ["evaltype", "custom_expression", ["formula"]],
542 ]
543 ),
544 status=dict(
545 type="str",
546 required=False,
547 default="enabled",
548 choices=["enabled", "disabled"],
549 ),
550 state=dict(
551 type="str",
552 required=False,
553 default="present",
554 choices=["present", "absent"],
555 )
556 )
557 )
558
559 module = AnsibleModule(
560 argument_spec=argument_spec,
561 supports_check_mode=True,
562 )
563
564 name = module.params["name"]
565 description = module.params["description"]
566 operations = module.params["operations"]
567 filter_parameter = module.params["filter"]
568 status = module.params["status"]
569 state = module.params["state"]
570
571 correlation_class_obj = Correlation(module)
572 correlations = correlation_class_obj.get_correlations(name)
573
574 if state == "absent":
575 if len(correlations) == 1:
576 correlation_class_obj.delete_correlation(correlations[0])
577 else:
578 module.exit_json(changed=False)
579 else:
580 if len(correlations) == 1:
581 correlation_class_obj.update_correlation(correlations[0], description, operations, filter_parameter, status)
582 else:
583 correlation_class_obj.create_correlation(name, description, operations, filter_parameter, status)
584
585
586 if __name__ == "__main__":
587 main()