Debian Codegraph @

ansible_collections/community/zabbix/scripts/inventory/zabbix.py

raw
1 #!/usr/bin/env python
2
3 # (c) 2013, Greg Buehler
4 # (c) 2018, Filippo Ferrazini
5 #
6 # This file is part of Ansible,
7 #
8 # Ansible is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Ansible is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
20
21 ######################################################################
22
23 """
24 Zabbix Server external inventory script.
25 ========================================
26
27 Returns hosts and hostgroups from Zabbix Server.
28 If you want to run with --limit against a host group with space in the
29 name, use asterisk. For example --limit="Linux*servers".
30
31 Configuration is read from `zabbix.ini`.
32
33 Tested with Zabbix Server 2.0.6, 3.2.3 and 3.4.
34 """
35
36 from __future__ import print_function
37
38 import os
39 import sys
40 import argparse
41 import json
42 import atexit
43 from ansible.module_utils.six.moves import configparser
44 from ansible.module_utils.compat.version import LooseVersion
45 from ansible.module_utils.urls import Request
46 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
47
48
49 class ZabbixInventory(object):
50
51 def read_settings(self):
52 config = configparser.ConfigParser()
53 conf_path = "./zabbix.ini"
54 if not os.path.exists(conf_path):
55 conf_path = os.path.dirname(os.path.realpath(__file__)) + "/zabbix.ini"
56 if os.path.exists(conf_path):
57 config.read(conf_path)
58 # server
59 if config.has_option("zabbix", "server"):
60 self.zabbix_server = config.get("zabbix", "server")
61
62 # login
63 if config.has_option("zabbix", "username"):
64 self.zabbix_username = config.get("zabbix", "username")
65 if config.has_option("zabbix", "password"):
66 self.zabbix_password = config.get("zabbix", "password")
67 if config.has_option("zabbix", "auth_token"):
68 self.auth_token = config.get("zabbix", "auth_token")
69 # ssl certs
70 if config.has_option("zabbix", "validate_certs"):
71 if config.get("zabbix", "validate_certs") in ["false", "False", False]:
72 self.validate_certs = False
73 # timeout
74 if config.has_option("zabbix", "timeout"):
75 self.timeout = config.get("zabbix", "timeout")
76 # host inventory
77 if config.has_option("zabbix", "read_host_inventory"):
78 if config.get("zabbix", "read_host_inventory") in ["true", "True", True]:
79 self.read_host_inventory = True
80 # host interface
81 if config.has_option("zabbix", "use_host_interface"):
82 if config.get("zabbix", "use_host_interface") in ["false", "False", False]:
83 self.use_host_interface = False
84
85 def read_cli(self):
86 parser = argparse.ArgumentParser()
87 parser.add_argument("--host")
88 parser.add_argument("--list", action="store_true")
89 self.options = parser.parse_args()
90
91 def hoststub(self):
92 return {
93 "hosts": []
94 }
95
96 def api_request(self, method, params=None):
97 server_url = self.zabbix_server
98 validate_certs = self.validate_certs
99 timeout = self.timeout
100
101 headers = {"Content-Type": "application/json-rpc"}
102 payload = {
103 "jsonrpc": "2.0",
104 "method": method,
105 "id": "1"
106 }
107 if params is None:
108 payload["params"] = {}
109 else:
110 payload["params"] = params
111
112 if self.auth != "":
113 if (LooseVersion(self.zabbix_version) >= LooseVersion("7.0")):
114 headers["Authorization"] = "Bearer " + self.auth
115 else:
116 payload["auth"] = self.auth
117
118 api_url = server_url + "/api_jsonrpc.php"
119 req = Request(
120 headers=headers,
121 timeout=timeout,
122 validate_certs=validate_certs
123 )
124 try:
125 response = req.post(api_url, data=json.dumps(payload))
126 except ValueError:
127 print("Error: Something went wrong with JSON loading.", file=sys.stderr)
128 sys.exit(1)
129 except (URLError, HTTPError) as error:
130 print(error, file=sys.stderr)
131
132 return response
133
134 def get_version(self):
135 response = self.api_request(
136 "apiinfo.version"
137 )
138 res = json.load(response)
139 self.zabbix_version = res["result"]
140
141 def login_zabbix(self):
142 auth_token = self.auth_token
143 if auth_token:
144 self.auth = auth_token
145 return
146
147 atexit.register(self.logout_zabbix)
148
149 login_user = self.zabbix_username
150 login_password = self.zabbix_password
151 response = self.api_request(
152 "user.login",
153 {
154 "username": login_user,
155 "password": login_password
156 }
157 )
158 res = json.load(response)
159 self.auth = res["result"]
160
161 def logout_zabbix(self):
162 self.api_request(
163 "user.logout",
164 []
165 )
166
167 def get_host(self, name):
168 api_query = {"output": "extend", "selectGroups": "extend", "filter": {"host": [name]}}
169 if self.use_host_interface:
170 api_query["selectInterfaces"] = ["useip", "ip", "dns"]
171 if self.read_host_inventory:
172 api_query["selectInventory"] = "extend"
173
174 data = {"ansible_ssh_host": name}
175 if self.use_host_interface or self.read_host_inventory:
176 response = self.api_request("host.get", api_query)
177 response_obj = json.load(response)
178 if len(response_obj['result']) > 0:
179 host_data = response_obj['result'][0]
180 # check if zabbix api returned interfaces element
181 if "interfaces" in host_data:
182 # check for a interfaces list that contains at least interface
183 if len(host_data["interfaces"]) >= 1:
184 # use first interface only
185 if host_data["interfaces"][0]["useip"] == '0':
186 data["ansible_ssh_host"] = host_data["interfaces"][0]["dns"]
187 else:
188 data["ansible_ssh_host"] = host_data["interfaces"][0]["ip"]
189 if ("inventory" in host_data) and (host_data["inventory"]):
190 data.update(host_data["inventory"])
191 return data
192
193 def get_list(self):
194 api_query = {"output": "extend", "selectGroups": "extend"}
195 if self.use_host_interface:
196 api_query["selectInterfaces"] = ["useip", "ip", "dns"]
197 if self.read_host_inventory:
198 api_query["selectInventory"] = "extend"
199
200 response = self.api_request("host.get", api_query)
201 hosts_data = json.load(response)["result"]
202 data = {"_meta": {"hostvars": {}}}
203 data[self.defaultgroup] = self.hoststub()
204 for host in hosts_data:
205 hostname = host["name"]
206 hostvars = dict()
207 data[self.defaultgroup]["hosts"].append(hostname)
208
209 for group in host["groups"]:
210 groupname = group["name"]
211
212 if groupname not in data:
213 data[groupname] = self.hoststub()
214
215 data[groupname]["hosts"].append(hostname)
216 # check if zabbix api returned a interfaces element
217 if "interfaces" in host:
218 # check for a interfaces list that contains at least interface
219 if len(host["interfaces"]) >= 1:
220 # use first interface only
221 if host["interfaces"][0]["useip"] == 0:
222 hostvars["ansible_ssh_host"] = host["interfaces"][0]["dns"]
223 else:
224 hostvars["ansible_ssh_host"] = host["interfaces"][0]["ip"]
225 if ("inventory" in host) and (host["inventory"]):
226 hostvars.update(host["inventory"])
227 data["_meta"]["hostvars"][hostname] = hostvars
228
229 return data
230
231 def __init__(self):
232
233 self.defaultgroup = "group_all"
234 self.zabbix_server = None
235 self.zabbix_username = None
236 self.zabbix_password = None
237 self.auth_token = None
238 self.auth = ""
239 self.validate_certs = True
240 self.timeout = 30
241 self.read_host_inventory = False
242 self.use_host_interface = True
243 self.zabbix_version = ""
244
245 self.meta = {}
246
247 self.read_settings()
248 self.read_cli()
249
250 if self.zabbix_server and self.zabbix_username:
251 try:
252 self.get_version()
253 self.login_zabbix()
254 # zabbix_api tries to exit if it cannot parse what the zabbix server returned
255 # so we have to use SystemExit here
256 except (Exception, SystemExit) as e:
257 print("Error: got the exception '%s'. Check your zabbix.ini." % e, file=sys.stderr)
258 sys.exit(1)
259
260 if self.options.host:
261 data = self.get_host(self.options.host)
262 print(json.dumps(data, indent=2))
263
264 elif self.options.list:
265 data = self.get_list()
266 print(json.dumps(data, indent=2))
267
268 else:
269 print("usage: --list ..OR.. --host <hostname>", file=sys.stderr)
270 sys.exit(1)
271
272 else:
273 print("Error: Configuration of server and credentials are required. See zabbix.ini.", file=sys.stderr)
274 sys.exit(1)
275
276
277 ZabbixInventory()