Debian Codegraph @

ansible_collections/community/zabbix/plugins/modules/zabbix_connector.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 DOCUMENTATION = r"""
10 ---
11 module: zabbix_connector
12 short_description: Create/Delete/Update Zabbix connectors
13 description:
14 - This module allows you to create, modify and delete Zabbix connectors.
15 author:
16 - Loric Vandentempel (@loricvdt)
17 requirements:
18 - "python >= 3.9"
19 version_added: 3.3.0
20 options:
21 name:
22 description:
23 - Name of the connector.
24 type: str
25 required: true
26 url:
27 description:
28 - URL of the receiver used by the connector.
29 type: str
30 data_type:
31 description:
32 - Type of data being streamed.
33 type: str
34 choices: ["item_values", "events"]
35 item_value_types:
36 description:
37 - Parameter introduced in Zabbix 7.0
38 - List of value types to stream.
39 - Each element should be one of C(all), C(all+bin), C(numeric_float), C(character), C(log), C(numeric_unsigned), C(text) or C(binary).
40 - C(all) represents all types except binary I((default)).
41 - C(all+bin) represents all types, binary included.
42 type: list
43 elements: str
44 max_records:
45 description:
46 - Maximum number of records sent in one message.
47 type: int
48 max_senders:
49 description:
50 - Number of sender processes used by the connector.
51 type: int
52 max_attempts:
53 description:
54 - Maximum number of attempts.
55 type: int
56 attempt_interval:
57 description:
58 - Parameter introduced in Zabbix 7.0
59 - Interval between attempts in seconds (value between 0 and 10).
60 type: int
61 timeout:
62 description:
63 - Message sending timeout in seconds (value between 1 and 60).
64 type: int
65 http_proxy:
66 description:
67 - HTTP(S) proxy used by the connector.
68 type: str
69 auth_type:
70 description:
71 - HTTP authentication method used by the connector.
72 type: str
73 choices: ["none", "basic", "ntlm", "kerberos", "digest", "bearer"]
74 username:
75 description:
76 - Username to authenticate the connector with the receiver.
77 - Supported only if C(auth_type) is one of C(basic), C(ntlm), C(kerberos) or C(digest).
78 type: str
79 password:
80 description:
81 - Password to authenticate the connector with the receiver.
82 - Supported only if C(auth_type) is one of C(basic), C(ntlm), C(kerberos) or C(digest).
83 type: str
84 token:
85 description:
86 - Bearer token to authenticate the connector with the receiver.
87 - Required when C(auth_type=bearer).
88 type: str
89 verify_peer:
90 description:
91 - Whether the connector should verify the receiver's certificate.
92 type: bool
93 verify_host:
94 description:
95 - Whether the connector should verify the receiver's hostname against the certificate's CN or SAN fields.
96 type: bool
97 ssl_cert_file:
98 description:
99 - Public SSL key file path for client authentication.
100 type: str
101 ssl_key_file:
102 description:
103 - Private SSL key file path for client authentication.
104 type: str
105 ssl_key_password:
106 description:
107 - Password of the private SSL key file.
108 type: str
109 description:
110 description:
111 - Description of the connector.
112 type: str
113 enabled:
114 description:
115 - Whether the connector is enabled.
116 - (mapped to the I(status) property of the connector object in the Zabbix API)
117 type: bool
118 tags_eval_type:
119 description:
120 - Tag filter evaluation method.
121 type: str
122 choices: ["and/or", "or"]
123 tags:
124 description:
125 - List of tags to filter streamed data.
126 type: list
127 elements: dict
128 suboptions:
129 tag:
130 description:
131 - Name of the tag.
132 type: str
133 required: true
134 operator:
135 description:
136 - Conditional operator used to filter .
137 type: str
138 choices: ["equals", "does not equal", "contains", "does not contain", "exists", "does not exist"]
139 value:
140 description:
141 - Value of the tag compared.
142 type: str
143 state:
144 description:
145 - State of the connector.
146 - On C(present), it will create a connector if it does not exist or update the connector if the associated data is different.
147 - On C(absent), it will remove the connector if it exists.
148 type: str
149 choices: ["present", "absent"]
150 default: present
151
152 extends_documentation_fragment:
153 - community.zabbix.zabbix
154 """
155
156 EXAMPLES = r"""
157 # If you want to use Username and Password to be authenticated by Zabbix Server
158 - name: Set credentials to access Zabbix Server API
159 ansible.builtin.set_fact:
160 ansible_user: Admin
161 ansible_httpapi_pass: zabbix
162
163 # If you want to use API token to be authenticated by Zabbix Server
164 # https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/administration/general#api-tokens
165 - name: Set API token
166 ansible.builtin.set_fact:
167 ansible_zabbix_auth_key: 8ec0d52432c15c91fcafe9888500cf9a607f44091ab554dbee860f6b44fac895
168
169 - name: Create or update a connector
170 # set task level variables as we change ansible_connection plugin here
171 vars:
172 ansible_network_os: community.zabbix.zabbix
173 ansible_connection: httpapi
174 ansible_httpapi_port: 443
175 ansible_httpapi_use_ssl: true
176 ansible_httpapi_validate_certs: false
177 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
178 ansible_host: zabbix-example-fqdn.org
179 community.zabbix.zabbix_proxy:
180 name: My app connector
181 description: Connector to send item values to My app
182 state: present
183 enabled: true
184 data_type: item_values
185 url: https://my-app.example.com/api/zabbix-stream
186 auth_type: bearer
187 token: "{{ my_app_bearer_token }}"
188 value_types:
189 - numeric_float
190 - character
191 - numeric_unsigned
192 - text
193 tags_eval_type: and/or
194 tags:
195 - tag: to-my-app
196 operator: exists
197 - tag: privacy
198 operator: does not equal
199 value: hidden
200
201 - name: Delete a connector
202 # set task level variables as we change ansible_connection plugin here
203 vars:
204 ansible_network_os: community.zabbix.zabbix
205 ansible_connection: httpapi
206 ansible_httpapi_port: 443
207 ansible_httpapi_use_ssl: true
208 ansible_httpapi_validate_certs: false
209 ansible_zabbix_url_path: "zabbixeu" # If Zabbix WebUI runs on non-default (zabbix) path ,e.g. http://<FQDN>/zabbixeu
210 ansible_host: zabbix-example-fqdn.org
211 community.zabbix.zabbix_proxy:
212 name: My app connector
213 state: absent
214 """
215
216 RETURN = r"""
217 msg:
218 description: Text result of the operation.
219 returned: always
220 type: str
221 sample: "Successfully updated connector 'My app connector' (id: 2)"
222 result:
223 description: JSON result of the Zabbix API call
224 returned: success
225 type: dict
226 sample: '{"connectorids": ["2"]}'
227 """
228
229 from ansible.module_utils.basic import AnsibleModule
230
231 from ansible_collections.community.zabbix.plugins.module_utils.base import ZabbixBase
232 import ansible_collections.community.zabbix.plugins.module_utils.helpers as zabbix_utils
233
234
235 class Connector(ZabbixBase):
236
237 existing_data = None
238
239 DATA_TYPES = {
240 "item_values": "0",
241 "events": "1",
242 }
243
244 VALUE_TYPES = {
245 "numeric_float": 1,
246 "character": 2,
247 "log": 4,
248 "numeric_unsigned": 8,
249 "text": 10,
250 "binary": 20,
251 }
252
253 AUTH_TYPES = {
254 "none": "0",
255 "basic": "1",
256 "ntlm": "2",
257 "kerberos": "3",
258 "digest": "4",
259 "bearer": "5",
260 }
261
262 EVAL_TYPES = {
263 "and/or": "0",
264 "or": "2",
265 }
266
267 OPERATORS = {
268 "equals": "0",
269 "does not equal": "1",
270 "contains": "2",
271 "does not contain": "3",
272 "exists": "12",
273 "does not exist": "1",
274 }
275
276 def get_connector(self, name):
277 """
278 Gets the connector for the given name and returns its id, or None if it doesn't exist
279 :param name: name of the connector
280 :return: connector ID
281 """
282 try:
283 result = self._zapi.connector.get({
284 "filter": {"name": name},
285 "output": "extend",
286 "selectTags": ["tag", "operator", "value"]
287 })
288 if len(result) > 0 and "connectorid" in result[0]:
289 self.existing_data = result[0]
290 return result[0]["connectorid"]
291 else:
292 return None
293 except Exception as e:
294 self._module.fail_json(msg="Failed to get connector '%s': %s" % (name, e))
295
296 def add_connector(self, params):
297 """
298 Creates the connector with the given parameters
299 :param params: parameter dictionary (see Zabbix API)
300 """
301 try:
302 result = self._zapi.connector.create(params)
303 self._module.exit_json(changed=True, msg="Successfully created connector '%s'" % params["name"], result=result)
304 except Exception as e:
305 self._module.fail_json(msg="Failed to create connector '%s': %s" % (params["name"], e))
306
307 def update_connector(self, connector_id, params):
308 """
309 Updates the connector with the given ID with the provided updated parameters, only if they lead to changes
310 :param connector_id: ID of the connector to update
311 :param params: updated parameters
312 """
313 diff = {
314 k: v for k, v in params.items() if self.existing_data.get(k) != v
315 }
316 if diff == {}:
317 self._module.exit_json(
318 changed=False, msg="Connector '%s' (id: %s) already up to date" % (params["name"], connector_id), result={"connectorids": [str(connector_id)]})
319 else:
320 try:
321 diff["connectorid"] = connector_id
322 result = self._zapi.connector.update(diff)
323 self._module.exit_json(
324 changed=True, msg="Successfully updated connector '%s' (id: %s)" % (params["name"], connector_id), result=result)
325 except Exception as e:
326 self._module.fail_json(msg="Failed to update connector '%s': %s" % (params["name"], e))
327
328 def delete_connector(self, connector_id, name):
329 """
330 Deletes the connector with the given ID
331 :param connector_id: ID of the connector to delete
332 :param name: name opf the connector (only used for verbosity)
333 """
334 try:
335 result = self._zapi.connector.delete([connector_id])
336 self._module.exit_json(changed=True, msg="Successfully deleted connector '%s' (id: %s)" % (name, connector_id), result=result)
337 except Exception as e:
338 self._module.fail_json(msg="Failed to delete connector '%s': %s" % (name, e))
339
340 def sanitize_params(self, params):
341 """
342 Transforms the module parameters to their corresponding Zabbix API values
343 :param params: module parameters
344 :return: Zabbix API compatible parameters
345 """
346 sanitized = {
347 "name": params["name"],
348 "url": params["url"],
349 "data_type": Connector.DATA_TYPES.get(params["data_type"]),
350 "max_records": str(params["max_records"]) if params["max_records"] is not None else None,
351 "max_senders": str(params["max_senders"]) if params["max_senders"] is not None else None,
352 "max_attempts": str(params["max_attempts"]) if params["max_attempts"] is not None else None,
353 "attempt_interval": str(params["attempt_interval"]) if params["attempt_interval"] is not None else None,
354 "timeout": str(params["timeout"]) if params["timeout"] is not None else None,
355 "http_proxy": params["http_proxy"],
356 "authtype": Connector.AUTH_TYPES.get(params["auth_type"]),
357 "username": params["username"],
358 "password": params["password"],
359 "token": params["token"],
360 "verify_peer": str(int(params["verify_peer"])) if params["verify_peer"] is not None else None,
361 "verify_host": str(int(params["verify_host"])) if params["verify_host"] is not None else None,
362 "ssl_cert_file": params["ssl_cert_file"],
363 "ssl_key_file": params["ssl_key_file"],
364 "ssl_key_password": params["ssl_key_password"],
365 "description": params["description"],
366 "status": str(int(params["enabled"])) if params["enabled"] is not None else None,
367 "tags_evaltype": Connector.EVAL_TYPES.get(params["tags_eval_type"]),
368 }
369
370 if params["item_value_types"] is not None:
371 value_types = set(params["item_value_types"])
372 if "all" in value_types:
373 sanitized["item_value_type"] = "31"
374 elif "all+bin" in value_types:
375 sanitized["item_value_type"] = "51" # 31 + 20
376 else:
377 sum_value = 0
378 for value_type in value_types:
379 value = Connector.VALUE_TYPES.get(value_type)
380 if value is None:
381 self._module.fail_json(msg="'%s' is not a known value type, should be one of %s" %
382 (value_type, Connector.VALUE_TYPES.keys()))
383 sum_value += value
384 sanitized["item_value_type"] = str(sum_value)
385
386 if params["tags"] is not None:
387 tags = []
388 for tag_def in params["tags"]:
389 tag = {
390 "tag": tag_def["tag"],
391 "operator": Connector.OPERATORS.get(tag_def["operator"], 0),
392 "value": tag_def.get("value") or ""
393 }
394 tags.append(tag)
395 sanitized["tags"] = tags
396
397 return zabbix_utils.helper_cleanup_data(sanitized)
398
399
400 def main():
401 """
402 Main module entry point
403 """
404 argument_spec = zabbix_utils.zabbix_common_argument_spec()
405 argument_spec.update(dict(
406 name=dict(type="str", required=True),
407 url=dict(type="str"),
408 data_type=dict(type="str", choices=list(Connector.DATA_TYPES.keys())),
409 item_value_types=dict(type="list", elements="str"),
410 max_records=dict(type="int"),
411 max_senders=dict(type="int"),
412 max_attempts=dict(type="int"),
413 attempt_interval=dict(type="int"),
414 timeout=dict(type="int"),
415 http_proxy=dict(type="str"),
416 auth_type=dict(type="str", choices=list(Connector.AUTH_TYPES.keys())),
417 username=dict(type="str"),
418 password=dict(type="str", no_log=True),
419 token=dict(type="str", no_log=True),
420 verify_peer=dict(type="bool"),
421 verify_host=dict(type="bool"),
422 ssl_cert_file=dict(type="str"),
423 ssl_key_file=dict(type="str"),
424 ssl_key_password=dict(type="str", no_log=True),
425 description=dict(type="str"),
426 enabled=dict(type="bool"), # "status" in API
427 tags_eval_type=dict(type="str", choices=list(Connector.EVAL_TYPES.keys())),
428 tags=dict(
429 type="list",
430 elements="dict",
431 options=dict(
432 tag=dict(type="str", required=True),
433 operator=dict(type="str", choices=list(Connector.OPERATORS.keys())),
434 value=dict(type="str")
435 )
436 ),
437 state=dict(type="str", default="present", choices=["present", "absent"]),
438 ))
439 module = AnsibleModule(
440 argument_spec=argument_spec,
441 mutually_exclusive=[
442 ["username", "token"],
443 ["password", "token"],
444 ],
445 required_if=[
446 ["state", "present", ["data_type", "url"]],
447 ["auth_type", "basic", ["username", "password"]],
448 ["auth_type", "ntlm", ["username", "password"]],
449 ["auth_type", "kerberos", ["username", "password"]],
450 ["auth_type", "digest", ["username", "password"]],
451 ["auth_type", "bearer", ["token"]],
452 ],
453 )
454
455 name = module.params["name"]
456 state = module.params["state"]
457
458 connector = Connector(module)
459 connector_id = connector.get_connector(name)
460
461 if state == "absent":
462 if connector_id:
463 connector.delete_connector(connector_id, name)
464 else:
465 module.exit_json(changed=False, msg="Connector '%s' already absent" % name)
466 elif state == "present":
467 params = connector.sanitize_params(module.params)
468
469 if connector_id:
470 connector.update_connector(connector_id, params)
471 else:
472 connector.add_connector(params)
473
474
475 if __name__ == "__main__":
476 main()