Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Thierry Sallé (@seuf)
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 DOCUMENTATION = """
10 ---
11 module: grafana_dashboard
12 author:
13 - Thierry Sallé (@seuf)
14 version_added: "1.0.0"
15 short_description: Manage Grafana dashboards
16 description:
17 - Create, update, delete, export Grafana dashboards via API.
18 options:
19 org_id:
20 description:
21 - The Grafana organization ID where the dashboard will be imported / exported / deleted.
22 - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization.
23 - Mutually exclusive with C(org_name).
24 default: 1
25 type: int
26 org_name:
27 description:
28 - The Grafana organization name where the dashboard will be imported / exported / deleted.
29 - Not used when I(grafana_api_key) is set, because the grafana_api_key only belongs to one organization.
30 - Mutually exclusive with C(org_id).
31 type: str
32 folder:
33 description:
34 - UID of the folder where the dashboard will be created or imported.
35 - Required if C(parent_folder) is set.
36 default: General
37 version_added: "1.0.0"
38 type: str
39 parent_folder:
40 description:
41 - UID of the parent folder used to scope the search for the specified C(folder).
42 - Available with subfolder feature of Grafana 11.
43 version_added: "2.2.0"
44 type: str
45 state:
46 description:
47 - State of the dashboard.
48 choices: [ absent, export, present ]
49 default: present
50 type: str
51 slug:
52 description:
53 - Deprecated since Grafana 5. Use grafana dashboard uid instead.
54 - slug of the dashboard. It's the friendly url name of the dashboard.
55 - When C(state) is C(present), this parameter can override the slug in the meta section of the json file.
56 - If you want to import a json dashboard exported directly from the interface (not from the api),
57 you have to specify the slug parameter because there is no meta section in the exported json.
58 type: str
59 uid:
60 version_added: "1.0.0"
61 description:
62 - Used to identify the dashboard when C(state) is C(export) or C(absent).
63 - When C(state) is C(present), this can be used to set the UID during dashboard creation.
64 type: str
65 path:
66 description:
67 - The path to the json file containing the Grafana dashboard to import or export.
68 - A http URL is also accepted (since 2.10).
69 - Required if C(state) is C(export) or C(present).
70 aliases: [ dashboard_url ]
71 type: str
72 overwrite:
73 description:
74 - Override existing dashboard when state is present.
75 type: bool
76 default: false
77 dashboard_id:
78 description:
79 - Public Grafana.com dashboard id to import
80 version_added: "1.0.0"
81 type: str
82 dashboard_revision:
83 description:
84 - Revision of the public grafana dashboard to import
85 default: '1'
86 version_added: "1.0.0"
87 type: str
88 commit_message:
89 description:
90 - Set a commit message for the version history.
91 - Only used when C(state) is C(present).
92 type: str
93 extends_documentation_fragment:
94 - community.grafana.basic_auth
95 - community.grafana.api_key
96 """
97
98 EXAMPLES = """
99 - name: Import Grafana dashboard foo
100 community.grafana.grafana_dashboard:
101 grafana_url: http://grafana.company.com
102 grafana_api_key: "{{ grafana_api_key }}"
103 state: present
104 commit_message: Updated by ansible
105 overwrite: true
106 path: /path/to/dashboards/foo.json
107
108 - name: Import Grafana dashboard Zabbix
109 community.grafana.grafana_dashboard:
110 grafana_url: http://grafana.company.com
111 grafana_api_key: "{{ grafana_api_key }}"
112 folder: zabbix
113 dashboard_id: 6098
114 dashboard_revision: 1
115
116 - name: Import Grafana dashboard zabbix
117 community.grafana.grafana_dashboard:
118 grafana_url: http://grafana.company.com
119 grafana_api_key: "{{ grafana_api_key }}"
120 folder: public
121 dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download
122
123 - name: Import Grafana dashboard zabbix in a subfolder
124 community.grafana.grafana_dashboard:
125 grafana_url: http://grafana.company.com
126 grafana_api_key: "{{ grafana_api_key }}"
127 parent_folder: public
128 folder: myteam
129 dashboard_url: https://grafana.com/api/dashboards/6098/revisions/1/download
130
131 - name: Export dashboard
132 community.grafana.grafana_dashboard:
133 grafana_url: http://grafana.company.com
134 grafana_user: "admin"
135 grafana_password: "{{ grafana_password }}"
136 org_id: 1
137 state: export
138 uid: "000000653"
139 path: "/path/to/dashboards/000000653.json"
140 """
141
142 RETURN = """
143 ---
144 uid:
145 description: uid or slug of the created / deleted / exported dashboard.
146 returned: success
147 type: str
148 sample: 000000063
149 """
150
151 import json
152 from ansible.module_utils.basic import AnsibleModule
153 from ansible.module_utils.urls import fetch_url
154 from ansible.module_utils.six.moves.urllib.parse import urlencode
155 from ansible.module_utils._text import to_native
156 from ansible.module_utils._text import to_text
157 from ansible_collections.community.grafana.plugins.module_utils.base import (
158 grafana_argument_spec,
159 clean_url,
160 parse_grafana_version,
161 )
162
163 __metaclass__ = type
164
165
166 class GrafanaAPIException(Exception):
167 pass
168
169
170 class GrafanaMalformedJson(Exception):
171 pass
172
173
174 class GrafanaExportException(Exception):
175 pass
176
177
178 class GrafanaDeleteException(Exception):
179 pass
180
181
182 def grafana_organization_id_by_name(module, grafana_url, org_name, headers):
183 r, info = fetch_url(
184 module, "%s/api/user/orgs" % grafana_url, headers=headers, method="GET"
185 )
186 if info["status"] != 200:
187 raise GrafanaAPIException("Unable to retrieve users organizations: %s" % info)
188 organizations = json.loads(to_text(r.read()))
189 for org in organizations:
190 if org["name"] == org_name:
191 return org["orgId"]
192
193 raise GrafanaAPIException(
194 "Current user isn't member of organization: %s" % org_name
195 )
196
197
198 def grafana_switch_organization(module, grafana_url, org_id, headers):
199 r, info = fetch_url(
200 module,
201 "%s/api/user/using/%s" % (grafana_url, org_id),
202 headers=headers,
203 method="POST",
204 )
205 if info["status"] != 200:
206 raise GrafanaAPIException(
207 "Unable to switch to organization %s : %s" % (org_id, info)
208 )
209
210
211 def grafana_headers(module, data):
212 headers = {"content-type": "application/json; charset=utf8"}
213 if "grafana_api_key" in data and data["grafana_api_key"]:
214 headers["Authorization"] = "Bearer %s" % data["grafana_api_key"]
215 else:
216 module.params["force_basic_auth"] = True
217 if module.params["org_name"]:
218 org_name = module.params["org_name"]
219 data["org_id"] = grafana_organization_id_by_name(
220 module, data["url"], org_name, headers
221 )
222 grafana_switch_organization(module, data["url"], data["org_id"], headers)
223
224 return headers
225
226
227 def get_grafana_version(module, grafana_url, headers):
228 grafana_version = {}
229 r, info = fetch_url(
230 module, "%s/api/frontend/settings" % grafana_url, headers=headers, method="GET"
231 )
232 if info["status"] == 200:
233 try:
234 settings = json.loads(to_text(r.read()))
235 grafana_version = parse_grafana_version(settings["buildInfo"]["version"])
236 except UnicodeError:
237 raise GrafanaAPIException("Unable to decode version string to Unicode")
238 except Exception as e:
239 raise GrafanaAPIException(e)
240 else:
241 raise GrafanaAPIException("Unable to get grafana version: %s" % info)
242
243 return grafana_version.get("major")
244
245
246 def grafana_folder_exists(module, grafana_url, folder_name, parent_folder, headers):
247 # the 'General' folder is a special case, it's ID is always '0'
248 if folder_name == "General":
249 return True, 0
250
251 try:
252 url = "%s/api/folders" % grafana_url
253 if parent_folder:
254 url = "%s?parentUid=%s" % (url, parent_folder)
255
256 r, info = fetch_url(module, url, headers=headers, method="GET")
257
258 if info["status"] != 200:
259 raise GrafanaAPIException(
260 "Unable to query Grafana API for folders (name: %s): %d"
261 % (folder_name, info["status"])
262 )
263
264 folders = json.loads(r.read())
265
266 for folder in folders:
267 if folder_name in (folder["title"], folder["uid"]):
268 return True, folder["id"]
269 except Exception as e:
270 raise GrafanaAPIException(e)
271
272 return False, 0
273
274
275 def grafana_dashboard_exists(module, grafana_url, uid, headers):
276 dashboard_exists = False
277 dashboard = {}
278
279 grafana_version = get_grafana_version(module, grafana_url, headers)
280 if grafana_version >= 5:
281 uri = "%s/api/dashboards/uid/%s" % (grafana_url, uid)
282 else:
283 uri = "%s/api/dashboards/db/%s" % (grafana_url, uid)
284
285 r, info = fetch_url(module, uri, headers=headers, method="GET")
286
287 if info["status"] == 200:
288 dashboard_exists = True
289 try:
290 dashboard = json.loads(r.read())
291 except Exception as e:
292 raise GrafanaAPIException(e)
293 elif info["status"] == 404:
294 dashboard_exists = False
295 else:
296 raise GrafanaAPIException("Unable to get dashboard %s : %s" % (uid, info))
297
298 return dashboard_exists, dashboard
299
300
301 def grafana_dashboard_search(module, grafana_url, folder_id, title, headers):
302 # search by title
303 uri = "%s/api/search?%s" % (
304 grafana_url,
305 urlencode({"folderIds": folder_id, "query": title, "type": "dash-db"}),
306 )
307 r, info = fetch_url(module, uri, headers=headers, method="GET")
308
309 if info["status"] == 200:
310 try:
311 dashboards = json.loads(r.read())
312 for d in dashboards:
313 if d["title"] == title:
314 return grafana_dashboard_exists(
315 module, grafana_url, d["uid"], headers
316 )
317 except Exception as e:
318 raise GrafanaAPIException(e)
319 else:
320 raise GrafanaAPIException("Unable to search dashboard %s : %s" % (title, info))
321
322 return False, None
323
324
325 # for comparison, we sometimes need to ignore a few keys
326 def is_grafana_dashboard_changed(payload, dashboard):
327 # you don't need to set the version, but '0' is incremented to '1' by Grafana's API
328 if "version" in payload["dashboard"]:
329 del payload["dashboard"]["version"]
330 if "version" in dashboard["dashboard"]:
331 del dashboard["dashboard"]["version"]
332
333 # if folderId is not provided in dashboard,
334 # try getting the folderId from the dashboard metadata,
335 # otherwise set the default folderId
336 if "folderId" not in dashboard:
337 dashboard["folderId"] = dashboard["meta"].get("folderId", 0)
338
339 # remove meta key if exists for compare
340 if "meta" in dashboard:
341 del dashboard["meta"]
342 if "meta" in payload:
343 del payload["meta"]
344
345 # Ignore dashboard ids since real identifier is uuid
346 if "id" in dashboard["dashboard"]:
347 del dashboard["dashboard"]["id"]
348 if "id" in payload["dashboard"]:
349 del payload["dashboard"]["id"]
350
351 if payload == dashboard:
352 return False
353 return True
354
355
356 def grafana_create_dashboard(module, data):
357 # define data payload for grafana API
358 payload = {}
359 if data.get("dashboard_id"):
360 data["path"] = "https://grafana.com/api/dashboards/%s/revisions/%s/download" % (
361 data["dashboard_id"],
362 data["dashboard_revision"],
363 )
364 if data["path"].startswith("http"):
365 r, info = fetch_url(module, data["path"])
366 if info["status"] != 200:
367 raise GrafanaAPIException(
368 "Unable to download grafana dashboard from url %s : %s"
369 % (data["path"], info)
370 )
371 payload = json.loads(r.read())
372 else:
373 try:
374 with open(data["path"], "r", encoding="utf-8") as json_file:
375 payload = json.load(json_file)
376 except Exception as e:
377 raise GrafanaAPIException("Can't load json file %s" % to_native(e))
378
379 # Check that the dashboard JSON is nested under the 'dashboard' key
380 if "dashboard" not in payload:
381 payload = {"dashboard": payload}
382
383 # define http header
384 headers = grafana_headers(module, data)
385
386 grafana_version = get_grafana_version(module, data["url"], headers)
387
388 if grafana_version < 5:
389 uid = data.get("slug") or payload.get("meta", {}).get("slug")
390 if not uid:
391 raise GrafanaMalformedJson("No slug found in JSON. Needed with Grafana < 5")
392 else:
393 uid = data.get("uid") or payload.get("dashboard", {}).get("uid")
394 if data.get("uid"):
395 payload["dashboard"]["uid"] = data["uid"]
396
397 result = {}
398
399 # test if the folder exists
400 folder_exists = False
401 if data["parent_folder"] and grafana_version < 11:
402 module.fail_json(
403 failed=True, msg="Subfolder API is available starting Grafana v11"
404 )
405
406 if grafana_version >= 5:
407 folder_exists, folder_id = grafana_folder_exists(
408 module, data["url"], data["folder"], data["parent_folder"], headers
409 )
410 if folder_exists is False:
411 raise GrafanaAPIException(
412 "Dashboard folder '%s' does not exist." % data["folder"]
413 )
414
415 payload["folderId"] = folder_id
416
417 # test if dashboard already exists
418 if uid:
419 dashboard_exists, dashboard = grafana_dashboard_exists(
420 module, data["url"], uid, headers=headers
421 )
422 else:
423 dashboard_exists, dashboard = grafana_dashboard_search(
424 module,
425 data["url"],
426 folder_id,
427 payload["dashboard"]["title"],
428 headers=headers,
429 )
430
431 if dashboard_exists is True:
432 grafana_dashboard_changed = is_grafana_dashboard_changed(payload, dashboard)
433
434 if grafana_dashboard_changed:
435 if module.check_mode:
436 module.exit_json(
437 uid=uid,
438 failed=False,
439 changed=True,
440 msg="Dashboard %s will be updated" % payload["dashboard"]["title"],
441 )
442 # update
443 if "overwrite" in data and data["overwrite"]:
444 payload["overwrite"] = True
445 if "commit_message" in data and data["commit_message"]:
446 payload["message"] = data["commit_message"]
447
448 r, info = fetch_url(
449 module,
450 "%s/api/dashboards/db" % data["url"],
451 data=json.dumps(payload),
452 headers=headers,
453 method="POST",
454 )
455 if info["status"] == 200:
456 if grafana_version >= 5:
457 try:
458 dashboard = json.loads(r.read())
459 uid = dashboard["uid"]
460 except Exception as e:
461 raise GrafanaAPIException(e)
462 result["uid"] = uid
463 result["msg"] = "Dashboard %s updated" % payload["dashboard"]["title"]
464 result["changed"] = True
465 else:
466 body = json.loads(info["body"])
467 raise GrafanaAPIException(
468 "Unable to update the dashboard %s : %s (HTTP: %d)"
469 % (uid, body["message"], info["status"])
470 )
471 else:
472 # unchanged
473 result["uid"] = uid
474 result["msg"] = "Dashboard %s unchanged." % payload["dashboard"]["title"]
475 result["changed"] = False
476 else:
477 if module.check_mode:
478 module.exit_json(
479 failed=False,
480 changed=True,
481 msg="Dashboard %s will be created" % payload["dashboard"]["title"],
482 )
483
484 # Ensure there is no id in payload
485 if "id" in payload["dashboard"]:
486 del payload["dashboard"]["id"]
487
488 r, info = fetch_url(
489 module,
490 "%s/api/dashboards/db" % data["url"],
491 data=json.dumps(payload),
492 headers=headers,
493 method="POST",
494 )
495 if info["status"] == 200:
496 result["msg"] = "Dashboard %s created" % payload["dashboard"]["title"]
497 result["changed"] = True
498 if grafana_version >= 5:
499 try:
500 dashboard = json.loads(r.read())
501 uid = dashboard["uid"]
502 except Exception as e:
503 raise GrafanaAPIException(e)
504 result["uid"] = uid
505 else:
506 raise GrafanaAPIException(
507 "Unable to create the new dashboard %s : %s - %s. (headers : %s)"
508 % (payload["dashboard"]["title"], info["status"], info, headers)
509 )
510
511 return result
512
513
514 def grafana_delete_dashboard(module, data):
515 # define http headers
516 headers = grafana_headers(module, data)
517
518 grafana_version = get_grafana_version(module, data["url"], headers)
519 if grafana_version < 5:
520 if data.get("slug"):
521 uid = data["slug"]
522 else:
523 raise GrafanaMalformedJson("No slug parameter. Needed with grafana < 5")
524 else:
525 if data.get("uid"):
526 uid = data["uid"]
527 else:
528 raise GrafanaDeleteException("No uid specified %s")
529
530 # test if dashboard already exists
531 dashboard_exists, dashboard = grafana_dashboard_exists(
532 module, data["url"], uid, headers=headers
533 )
534
535 result = {}
536 if dashboard_exists is True:
537 if module.check_mode:
538 module.exit_json(
539 uid=uid,
540 failed=False,
541 changed=True,
542 msg="Dashboard %s will be deleted" % uid,
543 )
544
545 # delete
546 if grafana_version < 5:
547 r, info = fetch_url(
548 module,
549 "%s/api/dashboards/db/%s" % (data["url"], uid),
550 headers=headers,
551 method="DELETE",
552 )
553 else:
554 r, info = fetch_url(
555 module,
556 "%s/api/dashboards/uid/%s" % (data["url"], uid),
557 headers=headers,
558 method="DELETE",
559 )
560 if info["status"] == 200:
561 result["msg"] = "Dashboard %s deleted" % uid
562 result["changed"] = True
563 result["uid"] = uid
564 else:
565 raise GrafanaAPIException(
566 "Unable to update the dashboard %s : %s" % (uid, info)
567 )
568 else:
569 # dashboard does not exist, do nothing
570 result = {
571 "msg": "Dashboard %s does not exist." % uid,
572 "changed": False,
573 "uid": uid,
574 }
575
576 return result
577
578
579 def grafana_export_dashboard(module, data):
580 # define http headers
581 headers = grafana_headers(module, data)
582
583 grafana_version = get_grafana_version(module, data["url"], headers)
584 if grafana_version < 5:
585 if data.get("slug"):
586 uid = data["slug"]
587 else:
588 raise GrafanaMalformedJson("No slug parameter. Needed with grafana < 5")
589 else:
590 if data.get("uid"):
591 uid = data["uid"]
592 else:
593 raise GrafanaExportException("No uid specified")
594
595 # test if dashboard already exists
596 dashboard_exists, dashboard = grafana_dashboard_exists(
597 module, data["url"], uid, headers=headers
598 )
599
600 if dashboard_exists is True:
601 if module.check_mode:
602 module.exit_json(
603 uid=uid,
604 failed=False,
605 changed=True,
606 msg="Dashboard %s will be exported to %s" % (uid, data["path"]),
607 )
608 try:
609 with open(data["path"], "w", encoding="utf-8") as f:
610 f.write(json.dumps(dashboard, indent=2))
611 except Exception as e:
612 raise GrafanaExportException("Can't write json file : %s" % to_native(e))
613 result = {
614 "msg": "Dashboard %s exported to %s" % (uid, data["path"]),
615 "uid": uid,
616 "changed": True,
617 }
618 else:
619 result = {
620 "msg": "Dashboard %s does not exist." % uid,
621 "uid": uid,
622 "changed": False,
623 }
624
625 return result
626
627
628 def main():
629 # use the predefined argument spec for url
630 argument_spec = grafana_argument_spec()
631 argument_spec.update(
632 state=dict(choices=["present", "absent", "export"], default="present"),
633 org_id=dict(default=1, type="int"),
634 org_name=dict(type="str"),
635 folder=dict(type="str", default="General"),
636 parent_folder=dict(type="str"),
637 uid=dict(type="str"),
638 slug=dict(type="str"),
639 path=dict(aliases=["dashboard_url"], type="str"),
640 dashboard_id=dict(type="str"),
641 dashboard_revision=dict(type="str", default="1"),
642 overwrite=dict(type="bool", default=False),
643 commit_message=dict(type="str"),
644 )
645 module = AnsibleModule(
646 argument_spec=argument_spec,
647 supports_check_mode=True,
648 required_if=[
649 ["state", "export", ["path"]],
650 ],
651 required_together=[["url_username", "url_password", "org_id"]],
652 mutually_exclusive=[
653 ["url_username", "grafana_api_key"],
654 ["uid", "slug"],
655 ["path", "dashboard_id"],
656 ["org_id", "org_name"],
657 ],
658 )
659
660 module.params["url"] = clean_url(module.params["url"])
661
662 try:
663 if module.params["state"] == "present":
664 result = grafana_create_dashboard(module, module.params)
665 elif module.params["state"] == "absent":
666 result = grafana_delete_dashboard(module, module.params)
667 else:
668 result = grafana_export_dashboard(module, module.params)
669 except GrafanaAPIException as e:
670 module.fail_json(failed=True, msg="error : %s" % to_native(e))
671 return
672 except GrafanaMalformedJson as e:
673 module.fail_json(failed=True, msg="error : %s" % to_native(e))
674 return
675 except GrafanaDeleteException as e:
676 module.fail_json(
677 failed=True, msg="error : Can't delete dashboard : %s" % to_native(e)
678 )
679 return
680 except GrafanaExportException as e:
681 module.fail_json(
682 failed=True, msg="error : Can't export dashboard : %s" % to_native(e)
683 )
684 return
685
686 module.exit_json(failed=False, **result)
687 return
688
689
690 if __name__ == "__main__":
691 main()