Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2022, 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_regexp
16
17 short_description: Create/update/delete Zabbix regular expression
18
19
20 description:
21 - This module allows you to create, update and delete Zabbix regular expression.
22
23 author:
24 - ONODERA Masaru(@masa-orca)
25
26 requirements:
27 - "python >= 3.9"
28
29 version_added: 2.1.0
30
31 options:
32 name:
33 description:
34 - Name of this regular expression
35 type: str
36 required: true
37 test_string:
38 description:
39 - A test string for this regular expression
40 type: str
41 expressions:
42 description:
43 - List of expressions.
44 - The regular expression returns true when all expressions return true.
45 - Required when C(state=present).
46 type: list
47 elements: dict
48 suboptions:
49 expression:
50 description:
51 - A expression string
52 type: str
53 required: true
54 expression_type:
55 description:
56 - A expression string
57 type: str
58 required: true
59 choices:
60 - "character_string_included"
61 - "any_character_string_included"
62 - "character_string_not_included"
63 - "result_is_true"
64 - "result_is_false"
65 exp_delimiter:
66 description:
67 - Delimiter for expression.
68 - Used if expression_type is C(any_character_string_included).
69 - Default values is C(,)
70 type: str
71 choices: [",", ".", "/"]
72 case_sensitive:
73 description:
74 - If true, the expression will be case sensitive.
75 type: bool
76 default: false
77 state:
78 description:
79 - State of the regular expression.
80 type: str
81 choices: ['present', 'absent']
82 default: 'present'
83
84
85 notes:
86 - Only Zabbix >= 6.0 is supported.
87
88 extends_documentation_fragment:
89 - community.zabbix.zabbix
90
91 """
92
93 EXAMPLES = """
94 # If you want to use Username and Password to be authenticated by Zabbix Server
95 - name: Set credentials to access Zabbix Server API
96 ansible.builtin.set_fact:
97 ansible_user: Admin
98 ansible_httpapi_pass: zabbix
99
100 # If you want to use API token to be authenticated by Zabbix Server
101 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
102 - name: Set API token
103 ansible.builtin.set_fact:
104 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
105
106 - name: Update regexp of 'File systems for discovery'
107 # set task level variables as we change ansible_connection plugin here
108 vars:
109 ansible_network_os: community.zabbix.zabbix
110 ansible_connection: httpapi
111 ansible_httpapi_port: 443
112 ansible_httpapi_use_ssl: true
113 ansible_httpapi_validate_certs: false
114 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
115 ansible_host: zabbix-example-fqdn.org
116 community.zabbix.zabbix_regexp:
117 name: File systems for discovery
118 test_string: ext2
119 expressions:
120 - expression: "^(btrfs|ext2|ext3|ext4|reiser|xfs|ffs|ufs|jfs|jfs2|vxfs|hfs|apfs|refs|ntfs|fat32|zfs)$"
121 expression_type: result_is_true
122 """
123
124 RETURN = """
125 msg:
126 description: The result of the operation
127 returned: success
128 type: str
129 sample: 'Successfully updated regular expression setting'
130 """
131
132
133 from ansible.module_utils.basic import AnsibleModule
134
135 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
136 from ansible.module_utils.compat.version import LooseVersion
137
138 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
139
140
141 class RegularExpression(ZabbixBase):
142 def __init__(self, module, zbx=None, zapi_wrapper=None):
143 super(RegularExpression, self).__init__(module, zbx, zapi_wrapper)
144 if LooseVersion(self._zbx_api_version) < LooseVersion("6.0"):
145 module.fail_json(
146 msg="This module doesn't support Zabbix versions lower than 6.0"
147 )
148
149 def get_regexps(self, regexp_name):
150 try:
151 regexps = self._zapi.regexp.get(
152 {
153 "output": "extend",
154 "selectExpressions": [
155 "expression",
156 "expression_type",
157 "exp_delimiter",
158 "case_sensitive",
159 ],
160 "filter": {"name": regexp_name},
161 }
162 )
163 if len(regexps) >= 2:
164 self._module.fail_json("Too many regexps are matched.")
165 return regexps
166 except Exception as e:
167 self._module.fail_json(
168 msg="Failed to get regular expression setting: %s" % e
169 )
170
171 def delete_regexp(self, regexp):
172 try:
173 parameter = [regexp["regexpid"]]
174 if self._module.check_mode:
175 self._module.exit_json(changed=True)
176 self._zapi.regexp.delete(parameter)
177 self._module.exit_json(
178 changed=True, msg="Successfully deleted regular expression setting."
179 )
180 except Exception as e:
181 self._module.fail_json(
182 msg="Failed to delete regular expression setting: %s" % e
183 )
184
185 def _convert_expressions_to_json(self, expressions):
186 expression_type_values = [
187 "character_string_included",
188 "any_character_string_included",
189 "character_string_not_included",
190 "result_is_true",
191 "result_is_false",
192 ]
193
194 expression_jsons = []
195 for expression in expressions:
196 expression_json = {}
197
198 expression_json["expression"] = expression["expression"]
199 expression_type = zabbix_utils.helper_to_numeric_value(
200 expression_type_values, expression["expression_type"]
201 )
202 expression_json["expression_type"] = str(expression_type)
203 if expression["expression_type"] == "any_character_string_included":
204 if expression["exp_delimiter"]:
205 expression_json["exp_delimiter"] = expression["exp_delimiter"]
206 else:
207 expression_json["exp_delimiter"] = ","
208 elif expression["exp_delimiter"]:
209 self._module.warn(
210 "A value of exp_delimiter will be ignored because expression_type is not 'any_character_string_included'."
211 )
212 case_sensitive = "0"
213 if expression["case_sensitive"]:
214 case_sensitive = "1"
215 expression_json["case_sensitive"] = case_sensitive
216
217 expression_jsons.append(expression_json)
218 return expression_jsons
219
220 def create_regexp(self, name, test_string, expressions):
221 try:
222 if self._module.check_mode:
223 self._module.exit_json(changed=True)
224 self._zapi.regexp.create(
225 {
226 "name": name,
227 "test_string": test_string,
228 "expressions": self._convert_expressions_to_json(expressions),
229 }
230 )
231 self._module.exit_json(
232 changed=True, msg="Successfully created regular expression setting."
233 )
234 except Exception as e:
235 self._module.fail_json(
236 msg="Failed to create regular expression setting: %s" % e
237 )
238
239 def update_regexp(self, current_regexp, name, test_string, expressions):
240 try:
241 current_expressions = []
242 for expression in current_regexp["expressions"]:
243 if expression["expression_type"] != "1":
244 expression = zabbix_utils.helper_normalize_data(
245 expression, del_keys=["exp_delimiter"]
246 )[0]
247 current_expressions.append(expression)
248 future_expressions = self._convert_expressions_to_json(expressions)
249 diff_expressions = []
250 zabbix_utils.helper_compare_lists(
251 current_expressions, future_expressions, diff_expressions
252 )
253 if (
254 current_regexp["name"] == name
255 and current_regexp["test_string"] == test_string
256 and len(diff_expressions) == 0
257 ):
258 self._module.exit_json(changed=False)
259 else:
260 if self._module.check_mode:
261 self._module.exit_json(changed=True)
262 self._zapi.regexp.update(
263 {
264 "regexpid": current_regexp["regexpid"],
265 "name": name,
266 "test_string": test_string,
267 "expressions": future_expressions,
268 }
269 )
270 self._module.exit_json(
271 changed=True, msg="Successfully updated regular expression setting."
272 )
273 except Exception as e:
274 self._module.fail_json(
275 msg="Failed to update regular expression setting: %s" % e
276 )
277
278
279 def main():
280 """Main ansible module function"""
281
282 argument_spec = zabbix_utils.zabbix_common_argument_spec()
283 argument_spec.update(
284 dict(
285 name=dict(type="str", required=True),
286 test_string=dict(
287 type="str",
288 ),
289 expressions=dict(
290 type="list",
291 elements="dict",
292 options=dict(
293 expression=dict(type="str", required=True),
294 expression_type=dict(
295 type="str",
296 required=True,
297 choices=[
298 "character_string_included",
299 "any_character_string_included",
300 "character_string_not_included",
301 "result_is_true",
302 "result_is_false",
303 ],
304 ),
305 exp_delimiter=dict(type="str", choices=[",", ".", "/"]),
306 case_sensitive=dict(type="bool", default=False),
307 ),
308 ),
309 state=dict(
310 type="str",
311 required=False,
312 default="present",
313 choices=["present", "absent"],
314 ),
315 )
316 )
317
318 module = AnsibleModule(
319 argument_spec=argument_spec,
320 required_if=[["state", "present", ["expressions"]]],
321 supports_check_mode=True,
322 )
323
324 name = module.params["name"]
325 test_string = module.params["test_string"]
326 expressions = module.params["expressions"]
327 state = module.params["state"]
328
329 regexp_class_obj = RegularExpression(module)
330 regexps = regexp_class_obj.get_regexps(name)
331
332 if state == "absent":
333 if len(regexps) == 1:
334 regexp_class_obj.delete_regexp(regexps[0])
335 else:
336 module.exit_json(changed=False)
337 else:
338 if len(regexps) == 1:
339 regexp_class_obj.update_regexp(regexps[0], name, test_string, expressions)
340 else:
341 regexp_class_obj.create_regexp(name, test_string, expressions)
342
343
344 if __name__ == "__main__":
345 main()