Skip to content

Instantly share code, notes, and snippets.

@karel1980
Created September 8, 2023 09:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save karel1980/7e70d911777f28e26e713c14dea53c0f to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import sys
import json
import re
import requests
def sanitize(title):
cleaned = re.sub('[^a-zA-Z0-9]+', '_', title)
return cleaned.strip("_")
def download_all(base_path, api_key, target_dir):
dashboards = json.loads(requests.get('%s/search'%(base_path), headers={"Authorization": "Bearer %s"%(api_key)}).text)
for board in dashboards:
type=board["type"]
if type == 'dash-db':
title=board['title']
folderId=board['folderId'] if 'folderId' in board else 'unknown'
folderTitle=board['folderTitle'] if 'folderTitle' in board else 'unknown'
uid=board['uid']
uri=board['uri']
sanitized_folder=sanitize(folderTitle)
sanitized_title=sanitize(title)
path="%s/%s/%s.json"%(target_dir, sanitized_folder, sanitized_title)
print(uid, path)
board_json = requests.get('%s/%s'%(base_path, uri), headers={"Authorization": "Bearer %s"%(api_key)}).text
print("writing %s"%(path))
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with open(path, 'w') as outfile:
outfile.write(board_json)
def help():
print("Usage: GRAFANA_API_KEY=ey...' %s https://grafana.example.com/api target-folder"%(sys.argv[0]))
print(" target-folder default to 'dashboards'")
def main():
if 'GRAFANA_API_KEY' not in os.environ:
help()
return
if len(sys.argv) < 2:
help()
return
grafana_api=sys.argv[1]
target_dir=sys.argv[2] if len(sys.argv) >= 3 else 'dashboards'
api_key = os.environ['GRAFANA_API_KEY']
download_all(grafana_api, api_key, target_dir)
if __name__=="__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment