传统运维 - 备份grafana图表
2024-10-23
导出
创建环境变量(/opt/grafana-env-config)
GRAFANA_URL=https://grafana.xx.com
GRAFANA_TOKEN=eyJrIjoiQTVySnlnMndsdsdM23QlJ1TWwwc09hMHBTTXFBdkEwYmZJMjciLCJuIjoidGVzdCIsImlkIjoxfQ==
# ${GRAFANA_URL}/org/apikeys新建
创建备份容器
docker run -it --rm --name=grafana-backup --env-file=/opt/grafana-env-config ysde/docker-grafana-backup-tool bash
开始备份,components参数可选值 <folders,dashboards,datasources,alert-channels,organizations,users>
grafana-backup save --components=dashboards,datasources,folders
导出备份结果(如创建容器使用-v,则可忽略本步骤)
docker cp grafana-backup:/opt/grafana-backup-tool/_OUTPUT_/202110190254.tar.gz /opt/grafana-backup/
导入
修改环境变量
docker exec -it grafana-backup bash
export GRAFANA_TOKEN=${xxx}
export GRAFANA_URL=${yyy}
还原图表
grafana-backup restore /opt/grafana-backup-tool/_OUTPUT_/202110190254.tar.gz
参考链接
https://cloud.tencent.com/developer/article/1766285
import os
import json
import requests
import datetime
import urllib.parse
grafana_domains = [
"https://grafana.xx.work",
]
dict = {
"https://grafana.xx.work": "eyJrIjoiQnRmbHVwZGpCb4VDUiLCJuIjoiYmFja3VwIiwiaWQiOjF9",
}
def backup_dashboard(grafana_domain, grafana_api_token):
"""备份单个 Grafana 域的所有仪表板"""
date = datetime.date.today().strftime("%Y-%m-%d")
parsed_url = urllib.parse.urlparse(grafana_domain)
domain_value = parsed_url.netloc
backup_dir = f"/opt/backup/grafana/{domain_value}/{date}"
os.makedirs(backup_dir, exist_ok=True)
headers = {"Authorization": f"Bearer {grafana_api_token}"}
resources = fetch_dashboards(grafana_domain, headers)
for resource in resources:
dashboard_uid = resource["uid"]
dashboard_folder_title = get_dashboard_folder_title(resource)
dashboard_title = resource["title"].replace(" ", "").replace("/", "_")
backup_single_dashboard(grafana_domain, dashboard_uid, dashboard_folder_title, dashboard_title, backup_dir, headers)
print(f"{grafana_domain} All dashboards backed up successfully.")
def fetch_dashboards(grafana_domain, headers):
"""获取所有仪表板的 UID"""
response = requests.get(f"{grafana_domain}/api/search?type=dash-db", headers=headers).json()
return response
def get_dashboard_folder_title(resource):
"""获取仪表板文件夹标题"""
try:
return resource["folderTitle"].replace(" ", "").replace("/", "_")
except KeyError:
return "General"
def backup_single_dashboard(grafana_domain, dashboard_uid, dashboard_folder_title, dashboard_title, backup_dir, headers):
"""备份单个仪表板"""
dashboard_response = requests.get(f"{grafana_domain}/api/dashboards/uid/{dashboard_uid}", headers=headers).json()["dashboard"]
filename = f"{backup_dir}/dashboard--{dashboard_folder_title}--{dashboard_uid}--{dashboard_title}.json"
with open(filename, "w") as f:
json.dump(dashboard_response, f)
print(f"Dashboard {dashboard_uid} backed up to {filename}")
# 主程序
for grafana_domain in grafana_domains:
grafana_api_token = dict[grafana_domain]
backup_dashboard(grafana_domain, grafana_api_token)