grafana备份脚本

备份思路

1、逐个dashboard备份配置

2、每个dashboard保存成一个文件

3、文件名定义为 目录名-dashboard名.json

4、使用python2

5、其中http_header中生成的Authorization API KEY已过期,请自己重新生成后替换使用。

6、保存文件部分适配的是windows,若需要linux使用,需要自己修改。

grafana备份脚本_第1张图片

备份脚本

#!/usr/bin/python
# -*- coding:utf8 -*-
 
import requests
import json
import os
import datetime
 
 
class GrafanaHandler:
 
    def __init__(self):
        self.base_url = "http://127.0.0.1:3000"
        self.http_header = {"content-type": "application/json",
                            "Authorization": "Bearer xxxx"}
 
    def deal_req(self, req):
        if req.status_code == 200:
            return req.json()
        else:
            print "error_code:" + str(req.status_code)
            return
 
    def get(self, url, params={}):
        req = requests.get(url, params=params, headers=self.http_header)
        return self.deal_req(req)
 
    def post(self, url, params={}):
        pass
 
    def get_all_dashboard(self):
        api_url = "/api/search/"
        full_url = self.base_url + api_url
        params = {"type": "dash_db"}
        return self.get(full_url, params=params)
 
    def get_one_dashboard_conf_by_uid(self, uid):
        api_url = "/api/dashboards/uid/" + uid
        full_url = self.base_url + api_url
        return self.get(full_url)
 
 
if __name__ == "__main__":
    current_date = datetime.date.today().strftime("%Y%m%d")
    # 备份文件存放路径
    dir_path = "D:\\company\\grafana_backup\\" + current_date
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
 
    grafana_instance = GrafanaHandler()
    all_dashboard = grafana_instance.get_all_dashboard()
    for dashboard in all_dashboard:
        # 获取每个dashboard的配置
        dashboard_conf = grafana_instance.get_one_dashboard_conf_by_uid(dashboard["uid"])
        # 保存文件
        file_name = dashboard_conf["meta"]["folderTitle"] + "_" + dashboard_conf["dashboard"]["title"] + ".json"
        print file_name
        with open(dir_path + "\\" + file_name.replace("/", ""), "w") as f:
            f.write(json.dumps(dashboard_conf))

你可能感兴趣的:(prometheus,grafana)