Debian Codegraph @

ansible_collections/community/zabbix/plugins/inventory/zabbix_inventory.py

raw
1 #
2 # Copyright: (c), Ansible Project
3 #
4 # (c) 2023, Alexandre Georges
5 # (c) 2018, Filippo Ferrazini
6 # (c) 2013, Greg Buehler
7 # (c) 2021, Timothy Test
8 # Modified from ServiceNow Inventory Plugin and Zabbix inventory Script
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10
11 from __future__ import absolute_import, division, print_function
12 __metaclass__ = type
13
14 DOCUMENTATION = r"""
15 name: zabbix_inventory
16 author:
17 - Timothy Test (@ttestscripting)
18 short_description: Zabbix Inventory Plugin
19 version_added: 1.4.0
20 description:
21 - Zabbix Inventory plugin
22 - All vars from zabbix are prefixed with zbx_
23 requirements:
24 - "python >= 3.9"
25 options:
26 server_url:
27 description:
28 - URL of Zabbix server, with protocol (http or https).
29 C(url) is an alias for C(server_url).
30 required: true
31 type: str
32 aliases: [ url ]
33 env:
34 - name: ZABBIX_SERVER
35 proxy:
36 description: Proxy server to use for reaching zabbix API
37 type: string
38 default: ""
39 host_zapi_query:
40 description:
41 - API query for hosts - see zabbix documentation for more details U(https://www.zabbix.com/documentation/current/manual/api/reference/host/get)
42 type: dict
43 default: {}
44 suboptions:
45 selectApplications:
46 type: str
47 description:
48 - query
49 - Return an applications property with host applications.
50 - To return all values specify "extend"
51 - Can be limited to different fields for example setting the vaule to ["name"] will only return the name
52 - Additional fields can be specified by comma seperated value ["name", "field2"]
53 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/application/object) for more details on field names
54 selectDiscoveries:
55 type: str
56 description:
57 - query
58 - Return a discoveries property with host low-level discovery rules.
59 - To return all values specify 'extend'
60 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
61 - Additional fields can be specified by comma seperated value ['name', 'field2']
62 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/discoveryrule/object) for more details on field names
63 selectDiscoveryRule:
64 type: str
65 description:
66 - query
67 - Return a discoveryRule property with the low-level discovery rule that created the host (from host prototype in VMware monitoring).
68 - To return all values specify 'extend'
69 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
70 - Additional fields can be specified by comma seperated value ['name', 'field2']
71 - please see U(https://www.zabbix.com/documentation/current/manual/api/reference/discoveryrule/object) for more details on field names
72 selectGraphs:
73 type: str
74 description:
75 - query
76 - Return a discoveries property with host low-level discovery rules.
77 - To return all values specify 'extend'
78 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
79 - Additional fields can be specified by comma seperated value ['name', 'field2']
80 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/graph/object) for more details on field names
81 selectGroups:
82 type: str
83 description:
84 - query
85 - Return a groups property with host groups data that the host belongs to.
86 - To return all values specify 'extend'
87 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
88 - Additional fields can be specified by comma seperated value ['name', 'field2']
89 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/hostgroup/object) for more details on field names
90 selectHostDiscovery:
91 type: str
92 description:
93 - query
94 - Return a hostDiscovery property with host discovery object data.
95 - To return all values specify 'extend'
96 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
97 - Additional fields can be specified by comma seperated value ['name', 'field2']
98 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/host/get) for more details on field names
99 selectHttpTests:
100 type: str
101 description:
102 - query
103 - Return an httpTests property with host web scenarios.
104 - To return all values specify 'extend'
105 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
106 - Additional fields can be specified by comma seperated value ['name', 'field2']
107 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/httptest/object) for more details on field names
108 selectInterfaces:
109 type: str
110 description:
111 - query
112 - Return an interfaces property with host interfaces.
113 - To return all values specify 'extend'
114 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
115 - Additional fields can be specified by comma seperated value ['name', 'field2']
116 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/hostinterface/object) for more details on field names
117 selectInventory:
118 type: str
119 description:
120 - query
121 - Return an inventory property with host inventory data.
122 - To return all values specify 'extend'
123 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
124 - Additional fields can be specified by comma seperated value ['name', 'field2']
125 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/host/object#host_inventory) for more details on field names
126 selectItems:
127 type: str
128 description:
129 - query
130 - Return an items property with host items.
131 - To return all values specify 'extend'
132 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
133 - Additional fields can be specified by comma seperated value ['name', 'field2']
134 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/item/object) for more details on field names
135 selectMacros:
136 type: str
137 description:
138 - query
139 - Return a macros property with host macros.
140 - To return all values specify 'extend'
141 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
142 - Additional fields can be specified by comma seperated value ['name', 'field2']
143 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/usermacro/object) for more details on field names
144 selectParentTemplates:
145 type: str
146 description:
147 - query
148 - Return a parentTemplates property with templates that the host is linked to
149 - To return all values specify 'extend'
150 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
151 - Additional fields can be specified by comma seperated value ['name', 'field2']
152 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/template/object) for more details on field names
153 selectDashboards:
154 type: str
155 description:
156 - query
157 - Return a dashboards property.
158 - To return all values specify 'extend'
159 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
160 - Additional fields can be specified by comma seperated value ['name', 'field2']
161 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/templatedashboard/object) for more details on field names
162 selectTags:
163 type: str
164 description:
165 - query
166 - Return a tags property with host tags.
167 - To return all values specify 'extend'
168 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
169 - Additional fields can be specified by comma seperated value ['name', 'field2']
170 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/host/object#host_tag) for more details on field names
171 selectInheritedTags:
172 type: str
173 description:
174 - query
175 - Return an inheritedTags property with tags that are on all templates which are linked to host.
176 - To return all values specify 'extend'
177 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
178 - Additional fields can be specified by comma seperated value ['name', 'field2']
179 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/host/object#host_tag) for more details on field names
180 selectTriggers:
181 type: str
182 description:
183 - query
184 - Return a triggers property with host triggers.
185 - To return all values specify 'extend'
186 - Can be limited to different fields for example setting the vaule to ['name'] will only return the name
187 - Additional fields can be specified by comma seperated value ['name', 'field2']
188 - Please see U(https://www.zabbix.com/documentation/current/manual/api/reference/host/object#host_tag) for more details on field names
189 login_user:
190 description:
191 - Zabbix user name.
192 type: str
193 env:
194 - name: ZABBIX_USERNAME
195 login_password:
196 description:
197 - Zabbix user password.
198 type: str
199 env:
200 - name: ZABBIX_PASSWORD
201 auth_token:
202 description:
203 - Zabbix authentication token (see https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens)
204 - If provided then C(login_user) and C(login_password) are ignored
205 type: str
206 http_login_user:
207 description:
208 - Basic Auth login
209 type: str
210 http_login_password:
211 description:
212 - Basic Auth password
213 type: str
214 timeout:
215 description:
216 - The timeout of API request (seconds).
217 type: int
218 default: 10
219 validate_certs:
220 description:
221 - If set to False, SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.
222 type: bool
223 default: true
224 env:
225 - name: ZABBIX_VALIDATE_CERTS
226 add_zabbix_groups:
227 description:
228 - If set to True, hosts will be added to groups based on their zabbix groups
229 type: bool
230 default: false
231 extends_documentation_fragment:
232 - constructed
233 - inventory_cache
234 """
235
236 EXAMPLES = r"""
237 # Simple Inventory Plugin example
238 # This will create an inventory with details from zabbix such as applications name, applicaitonids, Parent Template Name, and group membership name
239 #It will also create 2 ansible inventory groups for enabled and disabled hosts in zabbix based on the status field.
240 plugin: community.zabbix.zabbix_inventory
241 server_url: https://zabbix.com
242 login_user: Admin
243 login_password: password
244 host_zapi_query:
245 selectApplications: ['name', 'applicationid']
246 selectParentTemplates: ['name']
247 selectGroups: ['name']
248 validate_certs: false
249 groups:
250 enabled: zbx_status == "0"
251 disabled: zbx_status == "1"
252
253
254 #Using Keyed Groups
255 plugin: community.zabbix.zabbix_inventory
256 server_url: https://zabbix.com
257 login_user: Admin
258 login_password: password
259 validate_certs: false
260 keyed_groups:
261 - key: zbx_status | lower
262 prefix: 'env'
263 - key: zbx_description | lower
264 prefix: 'test'
265 separator: ''
266
267 #Using proxy format of proxy is 'http://<user>:<pass>@<proxy>:<port>' or 'http://<proxy>:<port>'
268 plugin: community.zabbix.zabbix_inventory
269 server_url: https://zabbix.com
270 proxy: http://someproxy:8080
271 login_user: Admin
272 login_password: password
273 validate_certs: false
274
275 #Organize inventory groups based on zabbix host groups
276 plugin: community.zabbix.zabbix_inventory
277 server_url: https://zabbix.com
278 add_zabbix_groups: true
279 login_user: Admin
280 login_password: password
281 validate_certs: false
282
283 #Using compose to modify vars
284 plugin: community.zabbix.zabbix_inventory
285 server_url: https://zabbix.com
286 login_user: Admin
287 login_password: password
288 validate_certs: false
289 compose:
290 zbx_testvar: zbx_status.replace("1", "Disabled")
291
292 #Using auth token instead of username/password
293 plugin: community.zabbix.zabbix_inventory
294 server_url: https://zabbix.com
295 auth_token: 3bc3dc85e13e2431812e7a32fa8341cbcf378e5101356c015fdf2e35fd511b06
296 validate_certs: false
297
298 #Using jinga2 template for auth token instead of username/password.
299 plugin: community.zabbix.zabbix_inventory
300 server_url: https://zabbix.com
301 auth_token: "{{ lookup('ansible.builtin.env', 'ZABBIX_API_KEY') }}"
302 validate_certs: false
303 """
304
305 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable, to_safe_group_name
306 import os
307 import atexit
308 import json
309 from ansible.module_utils.urls import Request
310 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
311 from ansible.module_utils.compat.version import LooseVersion
312 from ansible.errors import AnsibleParserError
313
314
315 class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
316
317 NAME = 'community.zabbix.zabbix_inventory'
318
319 def __init__(self):
320 super().__init__()
321 self.auth = ''
322 self.zabbix_verion = ''
323
324 def api_request(self, method, params=None):
325 # set proxy information if required
326 proxy = self.get_option('proxy')
327 os.environ['http_proxy'] = proxy
328 os.environ['HTTP_PROXY'] = proxy
329 os.environ['https_proxy'] = proxy
330 os.environ['HTTPS_PROXY'] = proxy
331
332 server_url = self.get_option('server_url')
333 validate_certs = self.get_option('validate_certs')
334 timeout = self.get_option('timeout')
335
336 headers = {'Content-Type': 'application/json-rpc'}
337 payload = {
338 'jsonrpc': '2.0',
339 'method': method,
340 'id': '1'
341 }
342 if params is None:
343 payload['params'] = {}
344 else:
345 payload['params'] = params
346
347 if self.auth != '':
348 if (LooseVersion(self.zabbix_version) >= LooseVersion('7.0')):
349 headers['Authorization'] = 'Bearer ' + self.auth
350 else:
351 payload['auth'] = self.auth
352
353 api_url = server_url + '/api_jsonrpc.php'
354 req = Request(
355 headers=headers,
356 timeout=timeout,
357 validate_certs=validate_certs
358 )
359 try:
360 self.display.vvv("Sending request to {0}".format(api_url))
361 response = req.post(api_url, data=json.dumps(payload))
362 except ValueError:
363 raise AnsibleParserError("something went wrong with JSON loading")
364 except (URLError, HTTPError) as error:
365 raise AnsibleParserError(error)
366
367 return response
368
369 def get_version(self):
370 response = self.api_request(
371 'apiinfo.version'
372 )
373 res = json.load(response)
374 self.zabbix_version = res['result']
375
376 def logout_zabbix(self):
377 self.api_request(
378 'user.logout',
379 []
380 )
381
382 def login_zabbix(self):
383 auth_token = self._template_option('auth_token')
384 if auth_token:
385 self.auth = auth_token
386 return
387
388 atexit.register(self.logout_zabbix)
389
390 login_user = self.get_option('login_user')
391 login_password = self.get_option('login_password')
392 response = self.api_request(
393 'user.login',
394 {
395 "username": login_user,
396 "password": login_password
397 }
398 )
399 res = json.load(response)
400 self.auth = res["result"]
401
402 def verify_file(self, path):
403 valid = False
404 if super(InventoryModule, self).verify_file(path):
405 if path.endswith(('zabbix_inventory.yaml', 'zabbix_inventory.yml')):
406 valid = True
407 else:
408 self.display.vvv(
409 'Skipping due to inventory source not ending in "zabbix_inventory.yaml" nor "zabbix_inventory.yml"')
410 return valid
411
412 def parse(self, inventory, loader, path,
413 cache=True): # Plugin interface (2)
414 super(InventoryModule, self).parse(inventory, loader, path)
415
416 self._read_config_data(path)
417 self.cache_key = self.get_cache_key(path)
418
419 self.use_cache = self.get_option('cache') and cache
420 self.update_cache = self.get_option('cache') and not cache
421
422 self.get_version()
423 self.login_zabbix()
424 zapi_query = self.get_option('host_zapi_query')
425 response = self.api_request(
426 'host.get',
427 zapi_query
428 )
429 res = json.load(response)
430 content = res['result']
431
432 strict = self.get_option('strict')
433
434 for record in content:
435 # add host to inventory
436 host_name = self.inventory.add_host(record['host'])
437 # set variables for host
438 for k in record.keys():
439 self.inventory.set_variable(host_name, 'zbx_%s' % k, record[k])
440
441 # added for compose vars and keyed groups
442 self._set_composite_vars(
443 self.get_option('compose'),
444 self.inventory.get_host(host_name).get_vars(), host_name, strict)
445
446 self._add_host_to_composed_groups(self.get_option('groups'), dict(), host_name, strict)
447 self._add_host_to_keyed_groups(self.get_option('keyed_groups'), dict(), host_name, strict)
448
449 # organize inventory by zabbix groups
450 if self.get_option('add_zabbix_groups'):
451
452 response = self.api_request(
453 'host.get',
454 {
455 'selectGroups': ['name']
456 }
457 )
458 res = json.load(response)
459 content = res['result']
460
461 for record in content:
462 host_name = record['host']
463 if len(record['groups']) >= 1:
464 for group in record['groups']:
465 group_name = to_safe_group_name(group['name'])
466 self.inventory.add_group(group_name)
467 self.inventory.add_child(group_name, host_name)
468
469 def _template_option(self, option):
470 value = self.get_option(option)
471 self.templar.available_variables = {}
472 return self.templar.template(value)