Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9
10 DOCUMENTATION = r'''
11 ---
12 module: zabbix_discoveryrule
13 short_description: Create/delete Zabbix low-level discovery (LLD) rules
14 description:
15 - Create discoveryrules if they do not exist.
16 - Delete existing discoveryrules if they exist.
17 author:
18 - "Andrew Lathrop (@aplathrop)"
19 requirements:
20 - "python >= 2.6"
21
22 options:
23 state:
24 description:
25 - Create or delete discovery rule.
26 required: false
27 type: str
28 default: "present"
29 choices: [ "present", "absent" ]
30 name:
31 description:
32 - Name of discovery rule to create or delete.
33 required: true
34 type: str
35 host_name:
36 description:
37 - Name of host to add discovery rule to.
38 - Required when I(template_name) is not used.
39 - Mutually exclusive with I(template_name).
40 required: false
41 type: str
42 template_name:
43 description:
44 - Name of template to add discovery rule to.
45 - Required when I(host_name) is not used.
46 - Mutually exclusive with I(host_name).
47 required: false
48 type: str
49 params:
50 description:
51 - Parameters to create/update discovery rule with.
52 - Required if state is "present".
53 - Parameters as defined at https://www.zabbix.com/documentation/current/en/manual/api/reference/discoveryrule/object
54 - Additionally supported parameters are below
55 required: false
56 type: dict
57 suboptions:
58 key:
59 description:
60 - LLD rule key.
61 - Alias for "key_" in API docs
62 required: false
63 type: str
64 interval:
65 description:
66 - Update interval of the LLD rule.
67 - Alias for "delay" in API docs
68 required: false
69 type: str
70 status:
71 description:
72 - Status of the LLD rule.
73 required: false
74 type: str
75 choices: [ "enabled", "disabled" ]
76 enabled:
77 description:
78 - Status of the LLD rule.
79 - Overrides "status" in API docs
80 required: false
81 type: bool
82 type:
83 description:
84 - Type of the LLD rule.
85 - Required if state is "present".
86 required: false
87 type: str
88 choices:
89 - zabbix_agent
90 - zabbix_trapper
91 - simple_check
92 - zabbix_internal
93 - zabbix_agent_active
94 - web_item
95 - external_check
96 - database_monitor
97 - ipmi_agent
98 - ssh_agent
99 - telnet_agent
100 - calculated
101 - jmx_agent
102 - snmp_trap
103 - dependent_item
104 - http_agent
105 - snmp_agent
106 - script
107 new_name:
108 description:
109 - New name for LLD rule.
110 required: false
111 type: str
112 preprocessing:
113 description:
114 - discovery rules preprocessing options.
115 - Parameters as defined at https://www.zabbix.com/documentation/current/en/manual/api/reference/discoveryrule/object#lld-rule-preprocessing
116 - Additionally supported parameters are below
117 required: false
118 type: list
119 elements: dict
120 suboptions:
121 type:
122 description:
123 - The preprocessing option type.
124 required: true
125 type: str
126 choices:
127 - xml_xpath
128 - jsonpath
129 - does_not_match_regular_expression
130 - not_match_regex
131 - check_for_error_in_json
132 - check_for_json_error
133 - check_for_error_in_xml
134 - check_for_xml_error
135 - discard_unchanged_with_heartbeat
136 - javascript
137 - prometheus_to_json
138 - csv_to_json
139 - replace
140 - xml_to_json
141 - snmp_walk_value
142 - snmp_walk_to_json
143 error_handler:
144 description:
145 - Action type used in case of preprocessing step failure.
146 required: false
147 type: str
148 choices:
149 - zabbix_server
150 - discard
151 - set_custom_value
152 - set_custom_error_message
153
154 extends_documentation_fragment:
155 - community.zabbix.zabbix
156 '''
157
158 EXAMPLES = r'''
159
160 # If you want to use Username and Password to be authenticated by Zabbix Server
161 - name: Set credentials to access Zabbix Server API
162 ansible.builtin.set_fact:
163 ansible_user: Admin
164 ansible_httpapi_pass: zabbix
165
166 # If you want to use API token to be authenticated by Zabbix Server
167 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
168 - name: Set API token
169 ansible.builtin.set_fact:
170 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
171
172 # Create LLD rule on example_host
173 - name: create rule
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_discoveryrule:
184 name: mounted_filesystem_discovery
185 host_name: example_host
186 params:
187 type: zabbix_agent
188 key: 'vfs.fs.discovery'
189 interval: 1h
190 enabled: True
191 state: present
192
193 # Create LLD rule on example_template
194 - name: create rule
195 # set task level variables as we change ansible_connection plugin here
196 vars:
197 ansible_network_os: community.zabbix.zabbix
198 ansible_connection: httpapi
199 ansible_httpapi_port: 443
200 ansible_httpapi_use_ssl: true
201 ansible_httpapi_validate_certs: false
202 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
203 ansible_host: zabbix-example-fqdn.org
204 community.zabbix.zabbix_discoveryrule:
205 name: mounted_filesystem_discovery
206 template_name: example_template
207 params:
208 type: zabbix_agent
209 key: 'vfs.fs.discovery'
210 interval: 1h
211 enabled: True
212 state: present
213
214 # Change interval for existing Zabbix LLD rule
215 - name: update rule
216 # set task level variables as we change ansible_connection plugin here
217 vars:
218 ansible_network_os: community.zabbix.zabbix
219 ansible_connection: httpapi
220 ansible_httpapi_port: 443
221 ansible_httpapi_use_ssl: true
222 ansible_httpapi_validate_certs: false
223 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
224 ansible_host: zabbix-example-fqdn.org
225 community.zabbix.zabbix_discoveryrule:
226 name: mounted_filesystem_discovery
227 template_name: example_template
228 params:
229 interval: 2h
230 state: present
231
232 # Delete LLD rule
233 - name: delete rule
234 # set task level variables as we change ansible_connection plugin here
235 vars:
236 ansible_network_os: community.zabbix.zabbix
237 ansible_connection: httpapi
238 ansible_httpapi_port: 443
239 ansible_httpapi_use_ssl: true
240 ansible_httpapi_validate_certs: false
241 ansible_zabbix_url_path: 'zabbixeu' # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
242 ansible_host: zabbix-example-fqdn.org
243 community.zabbix.zabbix_discoveryrule:
244 name: mounted_filesystem_discovery
245 template_name: example_template
246 state: absent
247
248 - name: Rename Zabbix LLD rule
249 # set task level variables as we change ansible_connection plugin here
250 vars:
251 ansible_network_os: community.zabbix.zabbix
252 ansible_connection: httpapi
253 ansible_httpapi_port: 443
254 ansible_httpapi_use_ssl: true
255 ansible_httpapi_validate_certs: false
256 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
257 ansible_host: zabbix-example-fqdn.org
258 community.zabbix.zabbix_discoveryrule:
259 name: mounted_filesystem_discovery
260 template_name: example_template
261 params:
262 new_name: new_mounted_filesystem_discovery
263 state: present
264 '''
265
266 from ansible.module_utils.basic import AnsibleModule
267
268 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
269 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
270
271
272 class Discoveryrule(ZabbixBase):
273 ITEM_TYPES = {'zabbix_agent': 0,
274 'zabbix_trapper': 2,
275 'simple_check': 3,
276 'zabbix_internal': 5,
277 'zabbix_agent_active': 7,
278 'web_item': 9,
279 'external_check': 10,
280 'database_monitor': 11,
281 'ipmi_agent': 12,
282 'ssh_agent': 13,
283 'telnet_agent': 14,
284 'calculated': 15,
285 'jmx_agent': 16,
286 'snmp_trap': 17,
287 'dependent_item': 18,
288 'http_agent': 19,
289 'snmp_agent': 20,
290 'script': 21}
291
292 PREPROCESSING_TYPES = {'regex': 5,
293 'xml_xpath': 11,
294 'jsonpath': 12,
295 'does_not_match_regular_expression': 15,
296 'not_match_regex': 15,
297 'check_for_error_in_json': 16,
298 'check_for_json_error': 16,
299 'check_for_error_in_xml': 17,
300 'check_for_xml_error': 17,
301 'discard_unchanged_with_heartbeat': 20,
302 'javascript': 21,
303 'prometheus_to_json': 23,
304 'csv_to_json': 24,
305 'replace': 25,
306 'xml_to_json': 27,
307 'snmp_walk_value': 28,
308 'snmp_walk_to_json': 29}
309
310 PREPROCESSING_ERROR_HANDLERS = {'zabbix_server': 0,
311 'discard': 1,
312 'set_custom_value': 2,
313 'set_custom_error_message': 3}
314
315 def get_hosts_templates(self, host_name, template_name):
316 if host_name is not None:
317 try:
318 return self._zapi.host.get({"filter": {"host": host_name}})
319 except Exception as e:
320 self._module.fail_json(msg="Failed to get host: %s" % e)
321 else:
322 try:
323 return self._zapi.template.get({"filter": {"host": template_name}})
324 except Exception as e:
325 self._module.fail_json(msg="Failed to get template: %s" % e)
326
327 def get_discoveryrules(self, discoveryrule_name, host_name, template_name):
328 if host_name is not None:
329 host = host_name
330 else:
331 host = template_name
332 discoveryrules = []
333 try:
334 discoveryrules = self._zapi.discoveryrule.get({'filter': {'name': discoveryrule_name, 'host': host}})
335 except Exception as e:
336 self._module.fail_json(msg="Failed to get discovery rules: %s" % e)
337 return discoveryrules
338
339 def sanitize_params(self, name, params):
340 params['name'] = name
341 if 'key' in params:
342 params['key_'] = params['key']
343 params.pop("key")
344 if 'type' in params:
345 item_type_int = self.ITEM_TYPES[params['type']]
346 params['type'] = item_type_int
347 if 'interval' in params:
348 params['delay'] = params['interval']
349 params.pop("interval")
350 if 'enabled' in params:
351 if params['enabled']:
352 params['status'] = 'enabled'
353 else:
354 params['status'] = 'disabled'
355 params.pop("enabled")
356 if 'status' in params:
357 status = params['status']
358 if status == 'enabled':
359 params['status'] = 0
360 elif status == 'disabled':
361 params['status'] = 1
362 else:
363 self._module.fail_json(msg="Status must be 'enabled' or 'disabled', got %s" % status)
364 if 'preprocessing' in params:
365 for param in params['preprocessing']:
366 preprocess_type_int = self.PREPROCESSING_TYPES[param['type']]
367 param['type'] = preprocess_type_int
368 if 'error_handler' in param:
369 error_handler_int = self.PREPROCESSING_ERROR_HANDLERS[param['error_handler']]
370 param['error_handler'] = error_handler_int
371
372 def add_discoveryrule(self, params):
373 if self._module.check_mode:
374 self._module.exit_json(changed=True)
375 try:
376 results = self._zapi.discoveryrule.create(params)
377 except Exception as e:
378 self._module.fail_json(msg="Failed to create discoveryrule: %s" % e)
379 return results
380
381 def update_discoveryrule(self, params):
382 if self._module.check_mode:
383 self._module.exit_json(changed=True)
384 try:
385 results = self._zapi.discoveryrule.update(params)
386 except Exception as e:
387 self._module.fail_json(msg="Failed to update discoveryrule: %s" % e)
388 return results
389
390 def check_discoveryrule_changed(self, old_discoveryrule):
391 try:
392 new_discoveryrule = self._zapi.discoveryrule.get({'itemids': "%s" % old_discoveryrule['itemid']})[0]
393 except Exception as e:
394 self._module.fail_json(msg="Failed to get discoveryrule: %s" % e)
395 return old_discoveryrule != new_discoveryrule
396
397 def delete_discoveryrule(self, discoveryrule_id):
398 if self._module.check_mode:
399 self._module.exit_json(changed=True)
400 try:
401 results = self._zapi.discoveryrule.delete(discoveryrule_id)
402 except Exception as e:
403 self._module.fail_json(msg="Failed to delete discoveryrule: %s" % e)
404 return results
405
406
407 def main():
408 argument_spec = zabbix_utils.zabbix_common_argument_spec()
409 argument_spec.update(dict(
410 name=dict(type='str', required=True),
411 host_name=dict(type='str', required=False),
412 template_name=dict(type='str', required=False),
413 params=dict(type='dict', required=False),
414 state=dict(type='str', default="present", choices=['present', 'absent']),
415 ))
416 module = AnsibleModule(
417 argument_spec=argument_spec,
418 required_one_of=[
419 ['host_name', 'template_name']
420 ],
421 mutually_exclusive=[
422 ['host_name', 'template_name']
423 ],
424 required_if=[
425 ['state', 'present', ['params']]
426 ],
427 supports_check_mode=True
428 )
429
430 name = module.params['name']
431 host_name = module.params['host_name']
432 template_name = module.params['template_name']
433 params = module.params['params']
434 state = module.params['state']
435
436 discoveryrule = Discoveryrule(module)
437
438 if state == "absent":
439 discoveryrules = discoveryrule.get_discoveryrules(name, host_name, template_name)
440 if len(discoveryrules) == 0:
441 module.exit_json(changed=False, result="No discoveryrule to delete.")
442 else:
443 delete_ids = []
444 for d in discoveryrules:
445 delete_ids.append(d['itemid'])
446 results = discoveryrule.delete_discoveryrule(delete_ids)
447 module.exit_json(changed=True, result=results)
448
449 elif state == "present":
450 discoveryrule.sanitize_params(name, params)
451 discoveryrules = discoveryrule.get_discoveryrules(name, host_name, template_name)
452 if 'new_name' in params:
453 new_name_discoveryrule = discoveryrule.get_discoveryrules(params['new_name'], host_name, template_name)
454 if len(new_name_discoveryrule) > 0:
455 module.exit_json(changed=False, result=[{'itemids': [new_name_discoveryrule[0]['itemid']]}])
456 results = []
457 if len(discoveryrules) == 0:
458 if 'new_name' in params:
459 module.fail_json('Cannot rename discoveryrule: %s is not found' % name)
460 hosts_templates = discoveryrule.get_hosts_templates(host_name, template_name)
461 for host_template in hosts_templates:
462 if 'hostid' in host_template:
463 params['hostid'] = host_template['hostid']
464 elif 'templateid' in host_template:
465 params['hostid'] = host_template['templateid']
466 else:
467 module.fail_json(msg="host/template did not return id")
468 results.append(discoveryrule.add_discoveryrule(params))
469 module.exit_json(changed=True, result=results)
470 else:
471 changed = False
472 for d in discoveryrules:
473 params['itemid'] = d['itemid']
474 if 'new_name' in params:
475 params['name'] = params['new_name']
476 params.pop("new_name")
477 results.append(discoveryrule.update_discoveryrule(params))
478 changed_rule = discoveryrule.check_discoveryrule_changed(d)
479 if changed_rule:
480 changed = True
481 module.exit_json(changed=changed, result=results)
482
483
484 if __name__ == '__main__':
485 main()