Debian Codegraph @

ansible_collections/community/zabbix/plugins/httpapi/zabbix.py

raw
1 # (c) 2021, Markus Fischbacher ([email protected])
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # Quick Link to Zabbix API docs: https://www.zabbix.com/documentation/current/manual/api
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 DOCUMENTATION = """
11 ---
12 name: zabbix
13 author:
14 - Markus Fischbacher (@rockaut)
15 - Evgeny Yurchenko (@BGmot)
16 short_description: HttpApi Plugin for Zabbix
17 description:
18 - This HttpApi plugin provides methods to connect to Zabbix over their HTTP(S)-based api.
19 version_added: 1.8.0
20 options:
21 zabbix_auth_key:
22 type: str
23 description:
24 - Specifies API authentication key
25 env:
26 - name: ANSIBLE_ZABBIX_AUTH_KEY
27 vars:
28 - name: ansible_zabbix_auth_key
29 zabbix_url_path:
30 type: str
31 description:
32 - Specifies path portion in Zabbix WebUI URL, e.g. for https://myzabbixfarm.com/zabbixeu zabbix_url_path=zabbixeu.
33 - "If Zabbix WebUI is running at the root, i.e. https://myzabbixfarm.com/, then assign empty string to this variable C(zabbix_url_path: '')."
34 default: zabbix
35 env:
36 - name: ANSIBLE_ZABBIX_URL_PATH
37 vars:
38 - name: ansible_zabbix_url_path
39 http_login_user:
40 type: str
41 description:
42 - The http user to access zabbix url with Basic Auth
43 vars:
44 - name: http_login_user
45 http_login_password:
46 type: str
47 description:
48 - The http password to access zabbix url with Basic Auth
49 vars:
50 - name: http_login_password
51 zabbix_http_headers:
52 type: dict
53 description:
54 - A dictionary of additional HTTP headers to be sent with every request to the Zabbix API.
55 - These headers are applied first, and can be overridden by plugin-specific headers like 'Authorization'.
56 vars:
57 - name: ansible_zabbix_http_headers
58 """
59
60 import json
61 import base64
62
63 from uuid import uuid4
64
65 from ansible.module_utils.basic import to_text
66 from ansible.errors import AnsibleConnectionFailure
67 from ansible.plugins.httpapi import HttpApiBase
68 from ansible.module_utils.compat.version import StrictVersion
69 from ansible.module_utils.connection import ConnectionError
70 from ansible.module_utils.common.parameters import remove_values
71
72
73 class HttpApi(HttpApiBase):
74 auth = None
75 url_path = "/zabbix" # By default Zabbix WebUI is on http(s)://FQDN/zabbix
76
77 def __init__(self, connection):
78 super().__init__(connection)
79 self.connection._auth = {"Content-Type": "application/json-rpc"}
80
81 def set_become(self, become_context):
82 """As this is an http rpc call there is no elevation available"""
83 pass
84
85 def update_auth(self, response, response_text):
86 return None
87
88 def login(self, username, password):
89 if auth_key := self.get_option("zabbix_auth_key"):
90 self.auth = auth_key
91 return
92
93 payload = self.payload_builder(
94 "user.login", username=username, password=password
95 )
96
97 code, response = self.send_request(data=payload)
98
99 if code == 200 and response != "":
100 self.auth = response
101
102 def logout(self):
103 if self.auth and not self.get_option("zabbix_auth_key"):
104 payload = self.payload_builder("user.logout")
105 self.send_request(data=payload)
106
107 def api_version(self):
108 url_path = self.get_option("zabbix_url_path")
109 if isinstance(url_path, str):
110 # zabbix_url_path provided (even if it is an empty string)
111 if url_path == "":
112 self.url_path = ""
113 else:
114 self.url_path = "/" + url_path
115 if not hasattr(self.connection, "zbx_api_version"):
116 code, version = self.send_request(
117 data=self.payload_builder("apiinfo.version")
118 )
119 if code == 200 and len(version) != 0:
120 self.connection.zbx_api_version = version
121 else:
122 raise ConnectionError(
123 "Could not get API version from Zabbix. Got HTTP code %s. Got version %s"
124 % (code, version)
125 )
126 return self.connection.zbx_api_version
127
128 def send_request(self, data, request_method="POST", path="/api_jsonrpc.php"):
129 headers = {}
130 # Apply custom headers first. Plugin-specific headers set later will take precedence.
131 custom_headers = self.get_option("zabbix_http_headers")
132 if isinstance(custom_headers, dict):
133 headers.update(custom_headers)
134
135 path = self.url_path + path
136
137 if self.auth and data["method"] not in ["user.login", "apiinfo.version"]:
138 if StrictVersion(self.api_version()) >= StrictVersion("6.4"):
139 headers["Authorization"] = "Bearer " + self.auth
140 else:
141 data["auth"] = self.auth
142
143 http_login_user = self.get_option("http_login_user")
144 http_login_password = self.get_option("http_login_password")
145 if http_login_user and http_login_user != "-42":
146 # Need to add Basic auth header
147 credentials = (http_login_user + ":" + http_login_password).encode("ascii")
148 headers["Authorization"] = "Basic " + base64.b64encode(credentials).decode(
149 "ascii"
150 )
151
152 try:
153 self._display_request(request_method, path, data["method"])
154 response, response_data = self.connection.send(
155 path, json.dumps(data), method=request_method, headers=headers
156 )
157 value = to_text(response_data.getvalue())
158
159 try:
160 json_data = json.loads(value) if value else {}
161 # JSONDecodeError only available on Python 3.5+
162 except ValueError:
163 raise ConnectionError("Invalid JSON response: %s" % value)
164
165 if "error" in json_data:
166 # Get this response from Zabbix when we switch username to execute REST API
167 if "re-login" in json_data["error"]["data"]:
168 # Need to login with new username/password
169 self.login(
170 self.connection.get_option("remote_user"),
171 self.connection.get_option("password"),
172 )
173 # Replace 'auth' field in payload with new one (we got from login process)
174 data["auth"] = self.connection._auth["auth"]
175 # Re-send the request we initially were trying to execute
176 response, response_data = self.connection.send(
177 path, json.dumps(data), method=request_method, headers=headers
178 )
179 value = to_text(response_data.getvalue())
180
181 try:
182 json_data = json.loads(value) if value else {}
183 # JSONDecodeError only available on Python 3.5+
184 except ValueError:
185 raise ConnectionError("Invalid JSON response: %s" % value)
186
187 if "error" in json_data:
188 raise ConnectionError(
189 "REST API returned %s when sending %s"
190 % (
191 json_data["error"],
192 remove_values(
193 data,
194 [
195 self.connection.get_option("password"),
196 ],
197 ),
198 )
199 )
200
201 if "result" in json_data:
202 json_data = json_data["result"]
203
204 try:
205 # Some methods return bool not a dict in "result"
206 iter(json_data)
207 except TypeError:
208 # Do not try to find "error" if it is not a dict
209 return response.getcode(), json_data
210
211 return response.getcode(), json_data
212
213 raise ConnectionError(
214 "REST API returned %s when sending %s"
215 % (
216 json_data["error"],
217 remove_values(
218 data,
219 [
220 self.connection.get_option("password"),
221 ],
222 ),
223 )
224 )
225
226 if "result" in json_data:
227 json_data = json_data["result"]
228
229 try:
230 # Some methods return bool not a dict in "result"
231 iter(json_data)
232 except TypeError:
233 # Do not try to find "error" if it is not a dict
234 return response.getcode(), json_data
235
236 return response.getcode(), json_data
237 except AnsibleConnectionFailure as e:
238 self.connection.queue_message("vvv", "AnsibleConnectionFailure: %s" % e)
239 if to_text("Could not connect to") in to_text(e):
240 raise
241 if to_text("401") in to_text(e):
242 return 401, "Authentication failure"
243 else:
244 return 404, "Object not found"
245 except Exception as e:
246 raise e
247
248 def _display_request(self, request_method, path, jsonrpc_method):
249 self.connection.queue_message(
250 "vvvv",
251 "Zabbix httpapi request: %s %s%s (%s)"
252 % (request_method, self.connection._url, path, jsonrpc_method),
253 )
254
255 def _get_response_value(self, response_data):
256 return to_text(response_data.getvalue())
257
258 def _response_to_json(self, response_text):
259 try:
260 return json.loads(response_text) if response_text else {}
261 # JSONDecodeError only available on Python 3.5+
262 except ValueError:
263 raise ConnectionError("Invalid JSON response: %s" % response_text)
264
265 @staticmethod
266 def payload_builder(method_, auth_=None, **kwargs):
267 reqid = str(uuid4())
268 req = {"jsonrpc": "2.0", "method": method_, "id": reqid}
269 req["params"] = kwargs
270
271 return req
272
273 def handle_httperror(self, exc):
274 # The method defined in ansible.plugins.httpapi
275 # We need to override it to avoid endless re-tries if HTTP authentication fails
276
277 if exc.code == 401:
278 return False
279
280 return exc