Debian Codegraph @

ansible_collections/community/grafana/plugins/modules/grafana_folder.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) 2019, Rémi REY (@rrey)
19
20 from __future__ import absolute_import, division, print_function
21
22 DOCUMENTATION = """
23 ---
24 module: grafana_folder
25 author:
26 - Rémi REY (@rrey)
27 version_added: "1.0.0"
28 short_description: Manage Grafana folders
29 description:
30 - Create/update/delete Grafana folders through the folders API.
31 requirements:
32 - The folders API is only available starting Grafana 5 and the module will fail if the server version is lower than version 5.
33 options:
34 name:
35 description:
36 - The title of the Grafana folder.
37 required: true
38 type: str
39 aliases: [ title ]
40 uid:
41 description:
42 - The folder UID.
43 type: str
44 parent_uid:
45 description:
46 - The parent folder UID.
47 - Available with subfolder feature of Grafana 11.
48 type: str
49 state:
50 description:
51 - Delete the members not found in the C(members) parameters from the
52 - list of members found on the folder.
53 default: present
54 type: str
55 choices: ["present", "absent"]
56 org_id:
57 description:
58 - Grafana organization ID in which the datasource should be created.
59 - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only
60 belongs to one organization.
61 - Mutually exclusive with C(org_name).
62 default: 1
63 type: int
64 org_name:
65 description:
66 - Grafana organization name in which the datasource should be created.
67 - Not used when C(grafana_api_key) is set, because the C(grafana_api_key) only
68 belongs to one organization.
69 - Mutually exclusive with C(org_id).
70 type: str
71 skip_version_check:
72 description:
73 - Skip Grafana version check and try to reach api endpoint anyway.
74 - This parameter can be useful if you enabled C(hide_version) in grafana.ini
75 required: False
76 type: bool
77 default: false
78 version_added: "1.2.0"
79 extends_documentation_fragment:
80 - community.grafana.basic_auth
81 - community.grafana.api_key
82 """
83
84 EXAMPLES = """
85 ---
86 - name: Create a folder
87 community.grafana.grafana_folder:
88 url: "https://grafana.example.com"
89 grafana_api_key: "{{ some_api_token_value }}"
90 title: "grafana_working_group"
91 state: present
92
93 - name: Delete a folder
94 community.grafana.grafana_folder:
95 url: "https://grafana.example.com"
96 grafana_api_key: "{{ some_api_token_value }}"
97 title: "grafana_working_group"
98 state: absent
99 """
100
101 RETURN = """
102 ---
103 folder:
104 description: Information about the folder
105 returned: On success
106 type: complex
107 contains:
108 id:
109 description: The folder identifier
110 returned: always
111 type: int
112 sample:
113 - 42
114 uid:
115 description: The folder uid
116 returned: always
117 type: str
118 sample:
119 - "nErXDvCkzz"
120 orgId:
121 description: The organization id
122 returned: always
123 type: int
124 sample:
125 - 1
126 title:
127 description: The folder title
128 returned: always
129 type: str
130 sample:
131 - "Department ABC"
132 url:
133 description: The folder url
134 returned: always
135 type: str
136 sample:
137 - "/dashboards/f/nErXDvCkzz/department-abc"
138 hasAcl:
139 description: Boolean specifying if folder has acl
140 returned: always
141 type: bool
142 sample:
143 - false
144 canSave:
145 description: Boolean specifying if current user can save in folder
146 returned: always
147 type: bool
148 sample:
149 - false
150 canEdit:
151 description: Boolean specifying if current user can edit in folder
152 returned: always
153 type: bool
154 sample:
155 - false
156 canAdmin:
157 description: Boolean specifying if current user can admin in folder
158 returned: always
159 type: bool
160 sample:
161 - false
162 createdBy:
163 description: The name of the user who created the folder
164 returned: always
165 type: str
166 sample:
167 - "admin"
168 created:
169 description: The folder creation date
170 returned: always
171 type: str
172 sample:
173 - "2018-01-31T17:43:12+01:00"
174 updatedBy:
175 description: The name of the user who last updated the folder
176 returned: always
177 type: str
178 sample:
179 - "admin"
180 updated:
181 description: The date the folder was last updated
182 returned: always
183 type: str
184 sample:
185 - "2018-01-31T17:43:12+01:00"
186 version:
187 description: The folder version
188 returned: always
189 type: int
190 sample:
191 - 1
192 parentUid:
193 description: The parent folders uid
194 returned: always as subfolder
195 type: str
196 sample:
197 - "76HjcBH2"
198 """
199
200 import json
201
202 from ansible.module_utils.basic import AnsibleModule
203 from ansible.module_utils.urls import fetch_url, basic_auth_header
204 from ansible_collections.community.grafana.plugins.module_utils import base
205 from ansible.module_utils._text import to_text
206
207 __metaclass__ = type
208
209
210 class GrafanaError(Exception):
211 pass
212
213
214 class GrafanaFolderInterface(object):
215 def __init__(self, module):
216 self._module = module
217 self.grafana_url = base.clean_url(module.params.get("url"))
218 self.org_id = None
219 # {{{ Authentication header
220 self.headers = {"Content-Type": "application/json"}
221 if module.params.get("grafana_api_key", None):
222 self.headers["Authorization"] = (
223 "Bearer %s" % module.params["grafana_api_key"]
224 )
225 else:
226 self.headers["Authorization"] = basic_auth_header(
227 module.params["url_username"], module.params["url_password"]
228 )
229 self.org_id = (
230 self.organization_by_name(module.params["org_name"])
231 if module.params["org_name"]
232 else module.params["org_id"]
233 )
234 self.switch_organization(self.org_id)
235 # }}}
236 if module.params.get("skip_version_check") is False:
237 try:
238 grafana_version = self.get_version()
239 except GrafanaError as e:
240 self._module.fail_json(failed=True, msg=to_text(e))
241 if grafana_version["major"] < 5:
242 self._module.fail_json(
243 failed=True, msg="folders API is available starting Grafana v5"
244 )
245 if grafana_version["major"] < 11 and module.params["parent_uid"]:
246 self._module.fail_json(
247 failed=True, msg="Subfolder API is available starting Grafana v11"
248 )
249
250 def _send_request(self, url, data=None, headers=None, method="GET"):
251 if data is not None:
252 data = json.dumps(data, sort_keys=True)
253 if not headers:
254 headers = []
255
256 full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url)
257 resp, info = fetch_url(
258 self._module, full_url, data=data, headers=headers, method=method
259 )
260 status_code = info["status"]
261 if status_code == 404:
262 return None
263 elif status_code == 401:
264 self._module.fail_json(
265 failed=True,
266 msg="Unauthorized to perform action '%s' on '%s'" % (method, full_url),
267 )
268 elif status_code == 403:
269 self._module.fail_json(failed=True, msg="Permission Denied")
270 elif status_code == 412:
271 error_msg = resp.read()["message"]
272 self._module.fail_json(failed=True, msg=error_msg)
273 elif status_code == 200:
274 # XXX: Grafana folders endpoint stopped sending back json in response for delete operations
275 # see https://github.com/grafana/grafana/issues/77673
276 response = resp.read() or "{}"
277 return self._module.from_json(response)
278 self._module.fail_json(
279 failed=True, msg="Grafana folders API answered with HTTP %d" % status_code
280 )
281
282 def switch_organization(self, org_id):
283 url = "/api/user/using/%d" % org_id
284 self._send_request(url, headers=self.headers, method="POST")
285
286 def organization_by_name(self, org_name):
287 url = "/api/user/orgs"
288 organizations = self._send_request(url, headers=self.headers, method="GET")
289 orga = next((org for org in organizations if org["name"] == org_name))
290 if orga:
291 return orga["orgId"]
292
293 self._module.fail_json(
294 failed=True, msg="Current user isn't member of organization: %s" % org_name
295 )
296
297 def get_version(self):
298 url = "/api/health"
299 response = self._send_request(
300 url, data=None, headers=self.headers, method="GET"
301 )
302 version = response.get("version")
303 if version is not None:
304 return base.parse_grafana_version(version)
305 raise GrafanaError("Failed to retrieve version from '%s'" % url)
306
307 def create_folder(self, title, uid=None, parent_uid=None):
308 url = "/api/folders"
309 folder = dict(title=title, uid=uid, parentUid=parent_uid)
310 response = self._send_request(
311 url, data=folder, headers=self.headers, method="POST"
312 )
313 return response
314
315 def get_folder(self, title, uid=None, parent_uid=None):
316 url = "/api/folders%s" % ("?parentUid=%s" % parent_uid if parent_uid else "")
317 response = self._send_request(url, headers=self.headers, method="GET")
318 if response:
319 if uid:
320 folders = [item for item in response if item.get("uid") == uid]
321 else:
322 folders = [
323 item for item in response if item.get("title") == to_text(title)
324 ]
325
326 if folders:
327 return folders[0]
328
329 return None
330
331 def delete_folder(self, folder_uid):
332 url = "/api/folders/%s" % folder_uid
333 response = self._send_request(url, headers=self.headers, method="DELETE")
334 return response
335
336
337 def main():
338 argument_spec = base.grafana_argument_spec()
339 argument_spec.update(
340 name=dict(type="str", aliases=["title"], required=True),
341 org_id=dict(default=1, type="int"),
342 org_name=dict(type="str"),
343 parent_uid=dict(type="str"),
344 skip_version_check=dict(type="bool", default=False),
345 state=dict(type="str", default="present", choices=["present", "absent"]),
346 uid=dict(type="str"),
347 )
348 module = AnsibleModule(
349 argument_spec=argument_spec,
350 supports_check_mode=False,
351 required_together=base.grafana_required_together()
352 + [["url_username", "url_password", "org_id"]],
353 mutually_exclusive=base.grafana_mutually_exclusive()
354 + [
355 ["org_id", "org_name"],
356 ],
357 )
358 state = module.params["state"]
359 title = module.params["name"]
360 parent_uid = module.params["parent_uid"]
361 uid = module.params["uid"]
362 module.params["url"] = base.clean_url(module.params["url"])
363
364 grafana_iface = GrafanaFolderInterface(module)
365
366 changed = False
367
368 folder = grafana_iface.get_folder(title, uid, parent_uid)
369
370 if state == "present":
371 if folder is None:
372 grafana_iface.create_folder(title, uid, parent_uid)
373 folder = grafana_iface.get_folder(title, uid, parent_uid)
374 changed = True
375 module.exit_json(changed=changed, folder=folder)
376 elif state == "absent":
377 if folder is None:
378 module.exit_json(changed=False, message="No folder found")
379 result = grafana_iface.delete_folder(folder.get("uid"))
380 module.exit_json(changed=True, message=result)
381
382
383 if __name__ == "__main__":
384 main()