Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2020, Tobias Birkefeld (@tcraxs) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r"""
11 ---
12 module: zabbix_discovery_rule
13 short_description: Create/delete/update Zabbix discovery rules
14 description:
15 - Create discovery rule.
16 - Delete existing discovery rule.
17 - Update existing discovery rule with new options.
18 author:
19 - "Tobias Birkefeld (@tcraxs)"
20 requirements:
21 - "python >= 3.9"
22 options:
23 state:
24 description:
25 - Create or delete discovery rules.
26 type: str
27 default: "present"
28 choices: [ "present", "absent" ]
29 name:
30 description:
31 - Name of the discovery rule.
32 required: true
33 type: str
34 iprange:
35 description:
36 - One or several IP ranges to check separated by commas.
37 type: list
38 elements: str
39 dchecks:
40 description:
41 - List of dictionaries of discovery check objects.
42 - For more information, review discovery check object documentation at
43 U(https://www.zabbix.com/documentation/current/manual/api/reference/dcheck/object)
44 suboptions:
45 type:
46 description:
47 - Type of check.
48 type: str
49 choices: ["SSH",
50 "LDAP",
51 "SMTP",
52 "FTP",
53 "HTTP",
54 "POP",
55 "NNTP",
56 "IMAP",
57 "TCP",
58 "Zabbix",
59 "SNMPv1",
60 "SNMPv2",
61 "ICMP",
62 "SNMPv3",
63 "HTTPS",
64 "Telnet"]
65 ports:
66 description:
67 - One or several port ranges to check separated by commas. Used for all checks except for ICMP.
68 type: str
69 key:
70 description:
71 - "The value of this property differs depending on the type of the check:"
72 - "- key to query for Zabbix agent checks"
73 - "- SNMP OID for SNMPv1, SNMPv2 and SNMPv3 checks"
74 type: str
75 snmp_community:
76 description:
77 - SNMP community.
78 - Required for SNMPv1 and SNMPv2 agent checks.
79 type: str
80 snmpv3_authpassphrase:
81 description:
82 - Authentication passphrase used for SNMPv3 agent checks with security level set to authNoPriv or authPriv.
83 type: str
84 snmpv3_authprotocol:
85 description:
86 - Authentication protocol used for SNMPv3 agent checks with security level set to authNoPriv or authPriv.
87 - "Possible values:"
88 - MD5
89 - SHA
90 type: str
91 choices: ["MD5", "SHA"]
92 snmpv3_contextname:
93 description:
94 - SNMPv3 context name. Used only by SNMPv3 checks.
95 type: str
96 snmpv3_privpassphrase:
97 description:
98 - Privacy passphrase used for SNMPv3 agent checks with security level set to authPriv.
99 type: str
100 snmpv3_privprotocol:
101 description:
102 - Privacy protocol used for SNMPv3 agent checks with security level set to authPriv.
103 - "Possible values:"
104 - DES
105 - AES
106 type: str
107 choices: ["DES", "AES"]
108 snmpv3_securitylevel:
109 description:
110 - Security level used for SNMPv3 agent checks.
111 - "Possible values:"
112 - noAuthNoPriv
113 - authNoPriv
114 - authPriv
115 type: str
116 choices: ["noAuthNoPriv", "authNoPriv", "authPriv"]
117 snmpv3_securityname:
118 description:
119 - Security name used for SNMPv3 agent checks.
120 type: str
121 uniq:
122 description:
123 - Whether to use this check as a device uniqueness criteria.
124 - Only a single unique check can be configured for a discovery rule.
125 - Used for Zabbix agent, SNMPv1, SNMPv2 and SNMPv3 agent checks.
126 - "Possible values:"
127 - "no - (default) do not use this check as a uniqueness criteria"
128 - "yes - use this check as a uniqueness criteria"
129 type: bool
130 default: no
131 host_source:
132 description:
133 - Source for host name.
134 - "Possible values:"
135 - "DNS (default)"
136 - "IP"
137 - "discovery - discovery value of this check"
138 - Options is available since Zabbix 4.4
139 type: str
140 default: "DNS"
141 choices: ["DNS", "IP", "discovery"]
142 name_source:
143 description:
144 - Source for visible name.
145 - "Possible values:"
146 - "none - (default) not specified"
147 - "DNS"
148 - "IP"
149 - "discovery - discovery value of this check"
150 - Options is available since Zabbix 4.4
151 type: str
152 default: "None"
153 choices: ["None", "DNS", "IP", "discovery"]
154 type: list
155 elements: dict
156 aliases: [ "dcheck" ]
157 delay:
158 description:
159 - Execution interval of the discovery rule.
160 - Accepts seconds, time unit with suffix and user macro.
161 type: str
162 default: "1h"
163 proxy:
164 description:
165 - Name of the proxy used for discovery.
166 type: str
167 status:
168 description:
169 - Whether the discovery rule is enabled.
170 - "Possible values:"
171 - enabled (default)
172 - disabled
173 type: str
174 default: "enabled"
175 choices: ["enabled", "disabled"]
176
177 extends_documentation_fragment:
178 - community.zabbix.zabbix
179 """
180
181 EXAMPLES = r"""
182 # If you want to use Username and Password to be authenticated by Zabbix Server
183 - name: Set credentials to access Zabbix Server API
184 ansible.builtin.set_fact:
185 ansible_user: Admin
186 ansible_httpapi_pass: zabbix
187
188 # If you want to use API token to be authenticated by Zabbix Server
189 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
190 - name: Set API token
191 ansible.builtin.set_fact:
192 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
193
194 # Base create discovery rule example
195 - name: Create discovery rule with ICMP and zabbix agent checks
196 # set task level variables as we change ansible_connection plugin here
197 vars:
198 ansible_network_os: community.zabbix.zabbix
199 ansible_connection: httpapi
200 ansible_httpapi_port: 443
201 ansible_httpapi_use_ssl: true
202 ansible_httpapi_validate_certs: false
203 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
204 ansible_host: zabbix-example-fqdn.org
205 community.zabbix.zabbix_discovery_rule:
206 name: ACME
207 state: present
208 iprange: 192.168.1.1-255
209 dchecks:
210 - type: ICMP
211 - type: Zabbix
212 key: "system.hostname"
213 ports: 10050
214 uniq: yes
215 host_source: "discovery"
216
217 # Base update (add new dcheck) discovery rule example
218 - name: Create discovery rule with ICMP and zabbix agent checks
219 # set task level variables as we change ansible_connection plugin here
220 vars:
221 ansible_network_os: community.zabbix.zabbix
222 ansible_connection: httpapi
223 ansible_httpapi_port: 443
224 ansible_httpapi_use_ssl: true
225 ansible_httpapi_validate_certs: false
226 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
227 ansible_host: zabbix-example-fqdn.org
228 community.zabbix.zabbix_discovery_rule:
229 name: ACME
230 state: present
231 iprange: 192.168.1.1-255
232 dchecks:
233 - type: SNMPv3
234 snmp_community: CUSTOMER@snmp3-readonly
235 ports: "161"
236 key: iso.3.6.1.2.1.1.1.0
237 snmpv3_contextname: "ContextName"
238 snmpv3_securityname: "SecurityName"
239 snmpv3_securitylevel: "authPriv"
240 snmpv3_authprotocol: "SHA"
241 snmpv3_authpassphrase: "SeCrEt"
242 snmpv3_privprotocol: "AES"
243 snmpv3_privpassphrase: "TopSecret"
244 uniq: no
245 host_source: "DNS"
246 name_source: "None"
247
248 # Base delete discovery rule example
249 - name: Delete discovery rule
250 # set task level variables as we change ansible_connection plugin here
251 vars:
252 ansible_network_os: community.zabbix.zabbix
253 ansible_connection: httpapi
254 ansible_httpapi_port: 443
255 ansible_httpapi_use_ssl: true
256 ansible_httpapi_validate_certs: false
257 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
258 ansible_host: zabbix-example-fqdn.org
259 community.zabbix.zabbix_discovery_rule:
260 name: ACME
261 state: absent
262 """
263
264 RETURN = r"""
265 state:
266 description: Discovery rule state at the end of execution.
267 returned: on success
268 type: str
269 sample: "present"
270 drule:
271 description: Discovery rule name.
272 returned: on success
273 type: str
274 sample: "ACME"
275 druleid:
276 description: Discovery rule id.
277 returned: on success
278 type: str
279 sample: "42"
280 msg:
281 description: The result of the operation
282 returned: always
283 type: str
284 sample: "Discovery rule created: ACME, ID: 42"
285 """
286
287
288 from ansible.module_utils.basic import AnsibleModule
289
290 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
291 from ansible.module_utils.compat.version import LooseVersion
292
293 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
294
295
296 class Dchecks(ZabbixBase):
297 """
298 Restructures the user defined discovery checks to fit the Zabbix API requirements
299 """
300
301 def construct_the_data(self, _dchecks):
302 """Construct the user defined discovery check to fit the Zabbix API
303 requirements
304 Args:
305 _dchecks: discovery checks to construct
306 Returns:
307 dict: user defined discovery checks
308 """
309 if _dchecks is None:
310 return None
311 constructed_data = []
312 for check in _dchecks:
313 constructed_check = {
314 "type": zabbix_utils.helper_to_numeric_value([
315 "SSH",
316 "LDAP",
317 "SMTP",
318 "FTP",
319 "HTTP",
320 "POP",
321 "NNTP",
322 "IMAP",
323 "TCP",
324 "Zabbix",
325 "SNMPv1",
326 "SNMPv2",
327 "ICMP",
328 "SNMPv3",
329 "HTTPS",
330 "Telnet"], check.get("type")
331 ),
332 "uniq": int(check.get("uniq"))
333 }
334 constructed_check.update({
335 "host_source": zabbix_utils.helper_to_numeric_value([
336 "None",
337 "DNS",
338 "IP",
339 "discovery"], check.get("host_source")
340 ),
341 "name_source": zabbix_utils.helper_to_numeric_value([
342 "None",
343 "DNS",
344 "IP",
345 "discovery"], check.get("name_source")
346 )
347 })
348 if constructed_check["type"] in (0, 1, 2, 3, 4, 5, 6, 7, 8, 14, 15):
349 constructed_check["ports"] = check.get("ports")
350 if constructed_check["type"] == 9:
351 constructed_check["ports"] = check.get("ports")
352 constructed_check["key_"] = check.get("key")
353 if constructed_check["type"] in (10, 11):
354 constructed_check["ports"] = check.get("ports")
355 constructed_check["snmp_community"] = check.get("snmp_community")
356 constructed_check["key_"] = check.get("key")
357 if constructed_check["type"] == 13:
358 constructed_check["ports"] = check.get("ports")
359 constructed_check["key_"] = check.get("key")
360 constructed_check["snmpv3_contextname"] = check.get("snmpv3_contextname")
361 constructed_check["snmpv3_securityname"] = check.get("snmpv3_securityname")
362 constructed_check["snmpv3_securitylevel"] = zabbix_utils.helper_to_numeric_value([
363 "noAuthNoPriv",
364 "authNoPriv",
365 "authPriv"], check.get("snmpv3_securitylevel")
366 )
367 if constructed_check["snmpv3_securitylevel"] in (1, 2):
368 constructed_check["snmpv3_authprotocol"] = zabbix_utils.helper_to_numeric_value([
369 "MD5",
370 "SHA"], check.get("snmpv3_authprotocol")
371 )
372 constructed_check["snmpv3_authpassphrase"] = check.get("snmpv3_authpassphrase")
373 if constructed_check["snmpv3_securitylevel"] == 2:
374 constructed_check["snmpv3_privprotocol"] = zabbix_utils.helper_to_numeric_value([
375 "DES",
376 "AES"], check.get("snmpv3_privprotocol")
377 )
378 constructed_check["snmpv3_privpassphrase"] = check.get("snmpv3_privpassphrase")
379 constructed_data.append(constructed_check)
380 return zabbix_utils.helper_cleanup_data(constructed_data)
381
382
383 class DiscoveryRule(ZabbixBase):
384 def check_if_drule_exists(self, name):
385 """Check if discovery rule exists.
386 Args:
387 name: Name of the discovery rule.
388 Returns:
389 The return value. True for success, False otherwise.
390 """
391 try:
392 _drule = self._zapi.drule.get({
393 "output": "extend",
394 "selectDChecks": "extend",
395 "filter": {"name": [name]}
396 })
397 if len(_drule) > 0:
398 return _drule
399 except Exception as e:
400 self._module.fail_json(msg="Failed to check if discovery rule '%s' exists: %s"
401 % (name, e))
402
403 def get_drule_by_drule_name(self, name):
404 """Get discovery rule by discovery rule name
405 Args:
406 name: discovery rule name.
407 Returns:
408 discovery rule matching discovery rule name
409 """
410 try:
411 drule_list = self._zapi.drule.get({
412 "output": "extend",
413 "selectDChecks": "extend",
414 "filter": {"name": [name]}
415 })
416 if len(drule_list) < 1:
417 self._module.fail_json(msg="Discovery rule not found: %s" % name)
418 else:
419 return drule_list[0]
420 except Exception as e:
421 self._module.fail_json(msg="Failed to get discovery rule '%s': %s" % (name, e))
422
423 def get_proxy_by_proxy_name(self, proxy_name):
424 """Get proxy by proxy name
425 Args:
426 proxy_name: proxy name.
427 Returns:
428 proxy matching proxy name
429 """
430 try:
431 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
432 proxy_list = self._zapi.proxy.get({
433 "output": "extend",
434 "selectInterface": "extend",
435 "filter": {"host": [proxy_name]}
436 })
437 else:
438 proxy_list = self._zapi.proxy.get({
439 "output": "extend",
440 "filter": {"name": [proxy_name]}
441 })
442
443 if len(proxy_list) < 1:
444 self._module.fail_json(msg="Proxy not found: %s" % proxy_name)
445 else:
446 return proxy_list[0]
447 except Exception as e:
448 self._module.fail_json(msg="Failed to get proxy '%s': %s" % (proxy_name, e))
449
450 def _construct_parameters(self, **kwargs):
451 """Construct parameters.
452 Args:
453 **kwargs: Arbitrary keyword parameters.
454 Returns:
455 dict: dictionary of specified parameters
456 """
457 _params = {
458 "name": kwargs["name"],
459 "iprange": ",".join(kwargs["iprange"]),
460 "delay": kwargs["delay"],
461 "status": zabbix_utils.helper_to_numeric_value([
462 "enabled",
463 "disabled"], kwargs["status"]
464 ),
465 "dchecks": kwargs["dchecks"]
466 }
467 if kwargs["proxy"]:
468 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
469 _params["proxy_hostid"] = self.get_proxy_by_proxy_name(kwargs["proxy"])["proxyid"]
470 else:
471 _params["proxyid"] = self.get_proxy_by_proxy_name(kwargs["proxy"])["proxyid"]
472
473 return _params
474
475 def check_difference(self, **kwargs):
476 """Check difference between discovery rule and user specified parameters.
477 Args:
478 **kwargs: Arbitrary keyword parameters.
479 Returns:
480 dict: dictionary of differences
481 """
482 existing_drule = zabbix_utils.helper_convert_unicode_to_str(self.check_if_drule_exists(kwargs["name"])[0])
483 parameters = zabbix_utils.helper_convert_unicode_to_str(self._construct_parameters(**kwargs))
484 change_parameters = {}
485 if LooseVersion(self._zbx_api_version) < LooseVersion("7.0"):
486 if existing_drule["nextcheck"]:
487 existing_drule.pop("nextcheck")
488 _diff = zabbix_utils.helper_cleanup_data(zabbix_utils.helper_compare_dictionaries(parameters, existing_drule, change_parameters))
489 return _diff
490
491 def update_drule(self, **kwargs):
492 """Update discovery rule.
493 Args:
494 **kwargs: Arbitrary keyword parameters.
495 Returns:
496 drule: updated discovery rule
497 """
498 try:
499 if self._module.check_mode:
500 self._module.exit_json(msg="Discovery rule would be updated if check mode was not specified: ID %s" % kwargs["drule_id"], changed=True)
501 kwargs["druleid"] = kwargs.pop("drule_id")
502 return self._zapi.drule.update(kwargs)
503 except Exception as e:
504 self._module.fail_json(msg="Failed to update discovery rule ID '%s': %s" % (kwargs["drule_id"], e))
505
506 def add_drule(self, **kwargs):
507 """Add discovery rule
508 Args:
509 **kwargs: Arbitrary keyword parameters
510 Returns:
511 drule: created discovery rule
512 """
513 try:
514 if self._module.check_mode:
515 self._module.exit_json(msg="Discovery rule would be added if check mode was not specified", changed=True)
516 parameters = self._construct_parameters(**kwargs)
517 drule_list = self._zapi.drule.create(parameters)
518 return drule_list["druleids"][0]
519 except Exception as e:
520 self._module.fail_json(msg="Failed to create discovery rule %s: %s" % (kwargs["name"], e))
521
522 def delete_drule(self, drule_id):
523 """Delete discovery rule.
524 Args:
525 drule_id: Discovery rule id
526 Returns:
527 drule: deleted discovery rule
528 """
529 try:
530 if self._module.check_mode:
531 self._module.exit_json(changed=True, msg="Discovery rule would be deleted if check mode was not specified")
532 return self._zapi.drule.delete([drule_id])
533 except Exception as e:
534 self._module.fail_json(msg="Failed to delete discovery rule '%s': %s" % (drule_id, e))
535
536
537 def main():
538 argument_spec = zabbix_utils.zabbix_common_argument_spec()
539 argument_spec.update(
540 name=dict(type="str", required=True),
541 iprange=dict(type="list", required=False, elements="str"),
542 dchecks=dict(
543 type="list",
544 required=False,
545 aliases=["dcheck"],
546 elements="dict",
547 options=dict(
548 type=dict(type="str", choices=[
549 "SSH",
550 "LDAP",
551 "SMTP",
552 "FTP",
553 "HTTP",
554 "POP",
555 "NNTP",
556 "IMAP",
557 "TCP",
558 "Zabbix",
559 "SNMPv1",
560 "SNMPv2",
561 "ICMP",
562 "SNMPv3",
563 "HTTPS",
564 "Telnet"]
565 ),
566 ports=dict(type="str"),
567 key=dict(type="str", no_log=False),
568 snmp_community=dict(type="str"),
569 snmpv3_authpassphrase=dict(type="str", no_log=True),
570 snmpv3_authprotocol=dict(type="str", choices=["MD5", "SHA"]),
571 snmpv3_contextname=dict(type="str"),
572 snmpv3_privpassphrase=dict(type="str", no_log=True),
573 snmpv3_privprotocol=dict(type="str", choices=["DES", "AES"]),
574 snmpv3_securitylevel=dict(type="str", choices=["noAuthNoPriv", "authNoPriv", "authPriv"]),
575 snmpv3_securityname=dict(type="str"),
576 uniq=dict(type="bool", default=False),
577 host_source=dict(type="str", choices=["DNS", "IP", "discovery"], default="DNS"),
578 name_source=dict(type="str", choices=["None", "DNS", "IP", "discovery"], default="None")
579 ),
580 required_if=[
581 ["type", "SSH", ["ports"]],
582 ["type", "LDAP", ["ports"]],
583 ["type", "SMTP", ["ports"]],
584 ["type", "FTP", ["ports"]],
585 ["type", "HTTP", ["ports"]],
586 ["type", "POP", ["ports"]],
587 ["type", "NNTP", ["ports"]],
588 ["type", "IMAP", ["ports"]],
589 ["type", "TCP", ["ports"]],
590 ["type", "Zabbix", ["ports", "key"]],
591 ["type", "SNMPv1", ["ports", "key", "snmp_community"]],
592 ["type", "SNMPv2", ["ports", "key", "snmp_community"]],
593 ["type", "SNMPv3", ["ports", "key"]],
594 ["type", "HTTPS", ["ports"]],
595 ["type", "Telnet", ["ports"]],
596 ["snmpv3_securitylevel", "authPriv", ["snmpv3_privpassphrase"]]
597 ]
598 ),
599 delay=dict(type="str", required=False, default="1h"),
600 proxy=dict(type="str", required=False, default=None),
601 status=dict(type="str", default="enabled", choices=["enabled", "disabled"]),
602 state=dict(type="str", default="present", choices=["present", "absent"])
603 )
604
605 module = AnsibleModule(
606 argument_spec=argument_spec,
607 required_if=[
608 ["state", "present", ["name", "iprange", "dchecks"]],
609 ["state", "absent", ["name"]],
610 ],
611 supports_check_mode=True
612 )
613
614 state = module.params["state"]
615 name = module.params["name"]
616 iprange = module.params["iprange"]
617 dchecks = module.params["dchecks"]
618 delay = module.params["delay"]
619 proxy = module.params["proxy"]
620 status = module.params["status"]
621
622 drule = DiscoveryRule(module)
623 zbx = drule._zapi
624 dcks = Dchecks(module, zbx)
625
626 drule_exists = drule.check_if_drule_exists(name)
627
628 if drule_exists:
629 drule_id = drule.get_drule_by_drule_name(name)["druleid"]
630 if state == "absent":
631 drule.delete_drule(drule_id)
632 module.exit_json(changed=True, state=state, drule=name, druleid=drule_id, msg="Discovery Rule deleted: %s, ID: %s" % (name, drule_id))
633 else:
634 difference = drule.check_difference(
635 drule_id=drule_id,
636 name=name,
637 iprange=iprange,
638 dchecks=dcks.construct_the_data(dchecks),
639 delay=delay,
640 proxy=proxy,
641 status=status
642 )
643
644 if difference == {}:
645 module.exit_json(changed=False, state=state, drule=name, druleid=drule_id, msg="Discovery Rule is up to date: %s" % name)
646 else:
647 drule_id = drule.update_drule(
648 drule_id=drule_id,
649 **difference
650 )
651 module.exit_json(changed=True, state=state, drule=name, druleid=drule_id, msg="Discovery Rule updated: %s, ID: %s" % (name, drule_id))
652 else:
653 if state == "absent":
654 module.exit_json(changed=False, state=state, drule=name, msg="Discovery rule %s does not exist, nothing to delete" % name)
655 else:
656 drule_id = drule.add_drule(
657 name=name,
658 iprange=iprange,
659 dchecks=dcks.construct_the_data(dchecks),
660 delay=delay,
661 proxy=proxy,
662 status=status
663 )
664 module.exit_json(changed=True, state=state, drule=name, druleid=drule_id, msg="Discovery Rule created: %s, ID: %s" % (name, drule_id))
665
666
667 if __name__ == "__main__":
668 main()