Debian Codegraph @

ansible_collections/community/grafana/plugins/modules/grafana_silence.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Copyright: (c) 2023, flkhndlr (@flkhndlr)
19
20 from __future__ import absolute_import, division, print_function
21
22 DOCUMENTATION = """
23 module: grafana_silence
24 author:
25 - flkhndlr (@flkhndlr)
26 version_added: "1.9.0"
27 short_description: Manage Grafana Silences
28 description:
29 - Create/delete Grafana Silences through the Alertmanager Silence API.
30 requirements:
31 - The Alertmanager API is only available starting Grafana 8 and the module will fail if the server version is lower than version 8.
32 options:
33 org_id:
34 description:
35 - The Grafana organization ID where the silence will be created or deleted.
36 - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization.
37 - Mutually exclusive with C(org_name).
38 default: 1
39 type: int
40 org_name:
41 description:
42 - The Grafana organization name where the silence will be created or deleted.
43 - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization.
44 - Mutually exclusive with C(org_id).
45 type: str
46 comment:
47 description:
48 - The comment that describes the silence.
49 required: true
50 type: str
51 created_by:
52 description:
53 - The author that creates the silence.
54 required: true
55 type: str
56 starts_at:
57 description:
58 - ISO 8601 Timestamp with milliseconds e.g. "2029-07-29T08:45:45.000Z" when the silence starts.
59 type: str
60 required: true
61 ends_at:
62 description:
63 - ISO 8601 Timestamp with milliseconds e.g. "2029-07-29T08:45:45.000Z" when the silence will end.
64 type: str
65 required: true
66 matchers:
67 description:
68 - List of matchers to select which alerts are affected by the silence.
69 type: list
70 elements: dict
71 required: true
72 state:
73 description:
74 - Delete the first occurrence of a silence with the same settings. Can be "absent" or "present".
75 default: present
76 type: str
77 choices: ["present", "absent"]
78 skip_version_check:
79 description:
80 - Skip Grafana version check and try to reach api endpoint anyway.
81 - This parameter can be useful if you enabled `hide_version` in grafana.ini
82 required: False
83 type: bool
84 default: False
85 extends_documentation_fragment:
86 - community.grafana.basic_auth
87 - community.grafana.api_key
88 """
89
90 EXAMPLES = """
91 ---
92 - name: Create a silence
93 community.grafana.grafana_silence:
94 grafana_url: "https://grafana.example.com"
95 grafana_api_key: "{{ some_api_token_value }}"
96 comment: "a testcomment"
97 created_by: "me"
98 starts_at: "2029-07-29T08:45:45.000Z"
99 ends_at: "2029-07-29T08:55:45.000Z"
100 matchers:
101 - isEqual: true
102 isRegex: true
103 name: environment
104 value: test
105 state: present
106
107 - name: Delete a silence
108 community.grafana.grafana_silence:
109 grafana_url: "https://grafana.example.com"
110 grafana_api_key: "{{ some_api_token_value }}"
111 comment: "a testcomment"
112 created_by: "me"
113 starts_at: "2029-07-29T08:45:45.000Z"
114 ends_at: "2029-07-29T08:55:45.000Z"
115 matchers:
116 - isEqual: true
117 isRegex: true
118 name: environment
119 value: test
120 state: absent
121 """
122
123 RETURN = """
124 ---
125 silence:
126 description: Information about the silence
127 returned: On success
128 type: complex
129 contains:
130 id:
131 description: The id of the silence
132 returned: success
133 type: str
134 sample:
135 - ec27df6b-ac3c-412f-ae0b-6e3e1f41c9c3
136 comment:
137 description: The comment of the silence
138 returned: success
139 type: str
140 sample:
141 - this is a test
142 createdBy:
143 description: The author of the silence
144 returned: success
145 type: str
146 sample:
147 - me
148 startsAt:
149 description: The begin timestamp of the silence
150 returned: success
151 type: str
152 sample:
153 - "2029-07-29T08:45:45.000Z"
154 endsAt:
155 description: The end timestamp of the silence
156 returned: success
157 type: str
158 sample:
159 - "2029-07-29T08:55:45.000Z"
160 matchers:
161 description: The matchers of the silence
162 returned: success
163 type: list
164 sample:
165 - [{"isEqual": true, "isRegex": true, "name": "environment", "value": "test"}]
166 status:
167 description: The status of the silence
168 returned: success
169 type: dict
170 sample:
171 - {"state": "pending"}
172 updatedAt:
173 description: The timestamp of the last update for the silence
174 returned: success
175 type: str
176 sample:
177 - "2023-07-27T13:27:33.042Z"
178 """
179
180 import json
181
182 from ansible.module_utils.basic import AnsibleModule
183 from ansible.module_utils.urls import fetch_url, basic_auth_header
184 from ansible.module_utils._text import to_text
185 from ansible_collections.community.grafana.plugins.module_utils import base
186
187 __metaclass__ = type
188
189
190 class GrafanaError(Exception):
191 pass
192
193
194 class GrafanaSilenceInterface(object):
195 def __init__(self, module):
196 self._module = module
197 self.grafana_url = base.clean_url(module.params.get("url"))
198 self.org_id = None
199 # {{{ Authentication header
200 self.headers = {"Content-Type": "application/json"}
201 if module.params.get("grafana_api_key", None):
202 self.headers["Authorization"] = (
203 "Bearer %s" % module.params["grafana_api_key"]
204 )
205 else:
206 self.headers["Authorization"] = basic_auth_header(
207 module.params["url_username"], module.params["url_password"]
208 )
209 self.org_id = (
210 self.organization_by_name(module.params["org_name"])
211 if module.params["org_name"]
212 else module.params["org_id"]
213 )
214 self.switch_organization(self.org_id)
215 # }}}
216
217 if module.params.get("skip_version_check") is False:
218 try:
219 grafana_version = self.get_version()
220 except GrafanaError as e:
221 self._module.fail_json(failed=True, msg=to_text(e))
222 if grafana_version["major"] < 8:
223 self._module.fail_json(
224 failed=True,
225 msg="Silences API is available starting with Grafana v8",
226 )
227
228 def _send_request(self, url, data=None, headers=None, method="GET"):
229 if data is not None:
230 data = json.dumps(data)
231 if not headers:
232 headers = []
233
234 full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url)
235 resp, info = fetch_url(
236 self._module, full_url, data=data, headers=headers, method=method
237 )
238 status_code = info["status"]
239 if status_code == 404:
240 return None
241 elif status_code == 401:
242 self._module.fail_json(
243 failed=True,
244 msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url),
245 )
246 elif status_code == 403:
247 self._module.fail_json(failed=True, msg="Permission Denied")
248 elif status_code in [200, 202]:
249 return self._module.from_json(resp.read())
250 elif status_code == 400:
251 self._module.fail_json(failed=True, msg=info)
252 self._module.fail_json(
253 failed=True, msg="Grafana Silences API answered with HTTP %d" % status_code
254 )
255
256 def switch_organization(self, org_id):
257 url = "/api/user/using/%d" % org_id
258 self._send_request(url, headers=self.headers, method="POST")
259
260 def organization_by_name(self, org_name):
261 url = "/api/user/orgs"
262 organizations = self._send_request(url, headers=self.headers, method="GET")
263 orga = next((org for org in organizations if org["name"] == org_name))
264 if orga:
265 return orga["orgId"]
266
267 return self._module.fail_json(
268 failed=True, msg="Current user isn't member of organization: %s" % org_name
269 )
270
271 def get_version(self):
272 url = "/api/health"
273 response = self._send_request(
274 url, data=None, headers=self.headers, method="GET"
275 )
276 version = response.get("version")
277 if version is not None:
278 return base.parse_grafana_version(version)
279 raise GrafanaError("Failed to retrieve version from '%s'" % url)
280
281 def create_silence(self, comment, created_by, starts_at, ends_at, matchers):
282 url = "/api/alertmanager/grafana/api/v2/silences"
283 silence = dict(
284 comment=comment,
285 createdBy=created_by,
286 endsAt=ends_at,
287 matchers=matchers,
288 startsAt=starts_at,
289 )
290 response = self._send_request(
291 url, data=silence, headers=self.headers, method="POST"
292 )
293 if self.get_version()["major"] == 8:
294 response["silenceID"] = response["id"]
295 response.pop("id", None)
296 return response
297
298 def get_silence(self, comment, created_by, starts_at, ends_at, matchers):
299 url = "/api/alertmanager/grafana/api/v2/silences"
300
301 responses = self._send_request(url, headers=self.headers, method="GET")
302
303 for response in responses:
304 if (
305 response["comment"] == comment
306 and response["createdBy"] == created_by
307 and response["startsAt"] == starts_at
308 and response["endsAt"] == ends_at
309 and response["matchers"] == matchers
310 ):
311 return response
312 return None
313
314 def get_silence_by_id(self, silence_id):
315 url = "/api/alertmanager/grafana/api/v2/silence/{SilenceId}".format(
316 SilenceId=silence_id
317 )
318 response = self._send_request(url, headers=self.headers, method="GET")
319 return response
320
321 def get_silences(self):
322 url = "/api/alertmanager/grafana/api/v2/silences"
323 response = self._send_request(url, headers=self.headers, method="GET")
324 return response
325
326 def delete_silence(self, silence_id):
327 url = "/api/alertmanager/grafana/api/v2/silence/{SilenceId}".format(
328 SilenceId=silence_id
329 )
330 response = self._send_request(url, headers=self.headers, method="DELETE")
331 return response
332
333
334 def setup_module_object():
335 module = AnsibleModule(
336 argument_spec=argument_spec,
337 supports_check_mode=False,
338 required_together=base.grafana_required_together(),
339 mutually_exclusive=base.grafana_mutually_exclusive(),
340 )
341 return module
342
343
344 argument_spec = base.grafana_argument_spec()
345 argument_spec.update(
346 comment=dict(type="str", required=True),
347 created_by=dict(type="str", required=True),
348 ends_at=dict(type="str", required=True),
349 matchers=dict(type="list", elements="dict", required=True),
350 org_id=dict(default=1, type="int"),
351 org_name=dict(type="str"),
352 skip_version_check=dict(type="bool", default=False),
353 starts_at=dict(type="str", required=True),
354 state=dict(type="str", choices=["present", "absent"], default="present"),
355 )
356
357
358 def main():
359 module = setup_module_object()
360 comment = module.params["comment"]
361 created_by = module.params["created_by"]
362 ends_at = module.params["ends_at"]
363 matchers = module.params["matchers"]
364 starts_at = module.params["starts_at"]
365 state = module.params["state"]
366
367 changed = False
368 failed = False
369 grafana_iface = GrafanaSilenceInterface(module)
370
371 silence = grafana_iface.get_silence(
372 comment, created_by, starts_at, ends_at, matchers
373 )
374
375 if state == "present":
376 if not silence:
377 silence = grafana_iface.create_silence(
378 comment, created_by, starts_at, ends_at, matchers
379 )
380 silence = grafana_iface.get_silence_by_id(silence["silenceID"])
381 changed = True
382 else:
383 module.exit_json(
384 failed=failed,
385 changed=changed,
386 msg="Silence with same parameters already exists! eg. '%s'"
387 % silence["id"],
388 )
389 elif state == "absent":
390 if silence:
391 grafana_iface.delete_silence(silence["id"])
392 changed = True
393 else:
394 module.exit_json(
395 failed=False,
396 changed=changed,
397 msg="Silence does not exist",
398 )
399
400 module.exit_json(failed=failed, changed=changed, silence=silence)
401
402
403 if __name__ == "__main__":
404 main()