Grafana API导出仪表板使用示例

Grafana API导出仪表板使用示例

快速开始

1. 获取API密钥

首先需要在Grafana中创建API密钥:

  1. 登录Grafana管理界面
  2. 访问 Configuration > API Keys
  3. 点击 New API Key
  4. 设置名称为 “dashboard-export”,权限选择 “Admin”
  5. 复制生成的API密钥

2. 设置环境变量

1
2
3
# 设置Grafana连接信息
export GRAFANA_URL="http://localhost:3000"
export GRAFANA_API_KEY="eyJrIjoiYWJjZGVmZ2hpams..."

使用Bash脚本

基本用法

1
2
3
4
5
6
# 导出所有仪表板
./export-dashboards.sh --api-key $GRAFANA_API_KEY

# 使用环境变量
export GRAFANA_API_KEY="your-api-key"
./export-dashboards.sh

高级用法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 导出特定文件夹的仪表板
./export-dashboards.sh --folder "Production" --api-key $GRAFANA_API_KEY

# 按标签过滤导出
./export-dashboards.sh --tag "monitoring" --api-key $GRAFANA_API_KEY

# 包含权限信息
./export-dashboards.sh --permissions --api-key $GRAFANA_API_KEY

# 详细输出模式
./export-dashboards.sh --verbose --api-key $GRAFANA_API_KEY

# 自定义输出目录
./export-dashboards.sh --output ./my-backups --api-key $GRAFANA_API_KEY

# 组合使用
./export-dashboards.sh \
    --url http://grafana.example.com \
    --api-key $GRAFANA_API_KEY \
    --folder "Production" \
    --permissions \
    --verbose \
    --output ./prod-backup

脚本输出示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$ ./export-dashboards.sh --api-key $GRAFANA_API_KEY
[INFO] 导出目录: ./grafana-exports/export_20241219_110000
[INFO] 测试Grafana连接...
[SUCCESS] 连接成功! 用户: admin, 组织: 1, 权限: Admin
[INFO] 获取文件夹列表...
[SUCCESS] 找到 3 个文件夹 (包括根文件夹)
[INFO] 导出数据源配置...
[SUCCESS] 数据源配置已导出: 2 个数据源
[INFO] 获取仪表板列表...
[SUCCESS] 找到 5 个仪表板
[1/5] [INFO] 导出仪表板: System Overview (UID: sys-overview)
[SUCCESS] 导出成功: System_Overview_sys-overview.json
[2/5] [INFO] 导出仪表板: Network Monitoring (UID: net-mon)
[SUCCESS] 导出成功: Network_Monitoring_net-mon.json
[3/5] [INFO] 导出仪表板: Application Metrics (UID: app-metrics)
[SUCCESS] 导出成功: Application_Metrics_app-metrics.json
[4/5] [INFO] 导出仪表板: Database Performance (UID: db-perf)
[SUCCESS] 导出成功: Database_Performance_db-perf.json
[5/5] [INFO] 导出仪表板: Custom Dashboard (UID: custom-dash)
[SUCCESS] 导出成功: Custom_Dashboard_custom-dash.json
[INFO] 生成导出报告...
[SUCCESS] 导出报告已生成: ./grafana-exports/export_20241219_110000/export_report.md

===========================================
[SUCCESS] 导出完成!
[INFO] 成功导出: 5/5 个仪表板
[INFO] 导出目录: ./grafana-exports/export_20241219_110000
[INFO] 查看报告: ./grafana-exports/export_20241219_110000/export_report.md

使用Python脚本

安装依赖

1
2
# 安装requests库
pip3 install requests

基本用法

1
2
3
4
5
6
# 导出所有仪表板
python3 export-grafana-dashboards.py --api-key $GRAFANA_API_KEY

# 使用环境变量
export GRAFANA_API_KEY="your-api-key"
python3 export-grafana-dashboards.py

高级用法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 导出特定文件夹
python3 export-grafana-dashboards.py \
    --api-key $GRAFANA_API_KEY \
    --folder "Production"

# 按标签过滤
python3 export-grafana-dashboards.py \
    --api-key $GRAFANA_API_KEY \
    --tag "monitoring"

# 包含权限信息
python3 export-grafana-dashboards.py \
    --api-key $GRAFANA_API_KEY \
    --include-permissions

# 不导出数据源和告警
python3 export-grafana-dashboards.py \
    --api-key $GRAFANA_API_KEY \
    --no-datasources \
    --no-alerts

# 详细输出
python3 export-grafana-dashboards.py \
    --api-key $GRAFANA_API_KEY \
    --verbose

# 完整示例
python3 export-grafana-dashboards.py \
    --url http://grafana.example.com \
    --api-key $GRAFANA_API_KEY \
    --output ./backups \
    --folder "Production" \
    --include-permissions \
    --timeout 60 \
    --verbose

Python脚本输出示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ python3 export-grafana-dashboards.py --api-key $GRAFANA_API_KEY
导出目录: ./grafana-exports/export_20241219_110000
开始导出Grafana配置...
Grafana URL: http://localhost:3000
测试Grafana连接...
✓ 连接成功! 用户: admin
  组织: 1
  权限: Admin
获取文件夹列表...
找到 3 个文件夹 (包括根文件夹)
导出数据源配置...
✓ 数据源配置已导出: 2 个数据源
导出告警规则...
✓ 告警规则已导出: 1 个规则
获取仪表板列表...
找到 5 个仪表板
[1/5] 导出仪表板: System Overview (UID: sys-overview)
  ✓ 导出成功: General/System_Overview_sys-overview.json
[2/5] 导出仪表板: Network Monitoring (UID: net-mon)
  ✓ 导出成功: Production/Network_Monitoring_net-mon.json
[3/5] 导出仪表板: Application Metrics (UID: app-metrics)
  ✓ 导出成功: Production/Application_Metrics_app-metrics.json
[4/5] 导出仪表板: Database Performance (UID: db-perf)
  ✓ 导出成功: Development/Database_Performance_db-perf.json
[5/5] 导出仪表板: Custom Dashboard (UID: custom-dash)
  ✓ 导出成功: General/Custom_Dashboard_custom-dash.json
✓ 导出报告已生成: ./grafana-exports/export_20241219_110000/export_report.md

==================================================
导出完成!
成功导出: 5/5 个仪表板
导出目录: ./grafana-exports/export_20241219_110000
查看报告: ./grafana-exports/export_20241219_110000/export_report.md

直接使用curl命令

快速导出单个仪表板

1
2
3
4
5
6
7
8
9
# 通过UID导出
curl -H "Authorization: Bearer $GRAFANA_API_KEY" \
     "$GRAFANA_URL/api/dashboards/uid/dashboard-uid" | \
     jq '.dashboard' > dashboard.json

# 通过slug导出
curl -H "Authorization: Bearer $GRAFANA_API_KEY" \
     "$GRAFANA_URL/api/dashboards/db/dashboard-slug" | \
     jq '.dashboard' > dashboard.json

批量导出所有仪表板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
# 简单的批量导出脚本

GRAFANA_URL="http://localhost:3000"
GRAFANA_API_KEY="your-api-key"
OUTPUT_DIR="./quick-export"

mkdir -p "$OUTPUT_DIR"

# 获取所有仪表板UID
curl -s -H "Authorization: Bearer $GRAFANA_API_KEY" \
     "$GRAFANA_URL/api/search?type=dash-db" | \
     jq -r '.[] | .uid' | \
while read uid; do
    echo "导出仪表板: $uid"
    curl -s -H "Authorization: Bearer $GRAFANA_API_KEY" \
         "$GRAFANA_URL/api/dashboards/uid/$uid" | \
         jq '.dashboard' > "$OUTPUT_DIR/dashboard_$uid.json"
done

echo "导出完成,文件保存在: $OUTPUT_DIR"

导出结果结构

目录结构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
grafana-exports/
└── export_20241219_110000/
    ├── folders.json                    # 文件夹信息
    ├── datasources.json               # 数据源配置
    ├── alerts.json                    # 告警规则
    ├── export_report.md               # 导出报告
    ├── General/                       # 根文件夹
       ├── System_Overview_sys-overview.json
       └── Custom_Dashboard_custom-dash.json
    ├── Production/                    # 生产环境文件夹
       ├── Network_Monitoring_net-mon.json
       └── Application_Metrics_app-metrics.json
    └── Development/                   # 开发环境文件夹
        └── Database_Performance_db-perf.json

仪表板JSON格式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
{
  "dashboard": {
    "id": null,
    "uid": "sys-overview",
    "title": "System Overview",
    "tags": ["system", "monitoring"],
    "timezone": "browser",
    "panels": [...],
    "time": {
      "from": "now-6h",
      "to": "now"
    },
    "timepicker": {...},
    "templating": {...},
    "annotations": {...},
    "refresh": "30s",
    "schemaVersion": 30,
    "version": 1
  },
  "meta": {
    "type": "db",
    "canSave": true,
    "canEdit": true,
    "canAdmin": true,
    "canStar": true,
    "slug": "system-overview",
    "url": "/d/sys-overview/system-overview",
    "expires": "0001-01-01T00:00:00Z",
    "created": "2024-01-01T00:00:00Z",
    "updated": "2024-12-19T10:00:00Z",
    "updatedBy": "admin",
    "createdBy": "admin",
    "version": 1,
    "hasAcl": false,
    "isFolder": false,
    "folderId": 1,
    "folderUid": "prod-folder",
    "folderTitle": "Production",
    "folderUrl": "/dashboards/f/prod-folder/production",
    "provisioned": false,
    "provisionedExternalId": ""
  },
  "folderTitle": "Production",
  "exportTime": "2024-12-19T11:00:00+08:00",
  "permissions": [
    {
      "id": 1,
      "dashboardId": 1,
      "created": "2024-01-01T00:00:00Z",
      "updated": "2024-01-01T00:00:00Z",
      "userId": 0,
      "userLogin": "",
      "userEmail": "",
      "teamId": 0,
      "team": "",
      "role": "Viewer",
      "permission": 1,
      "permissionName": "View",
      "uid": "",
      "title": "",
      "slug": "",
      "isFolder": false,
      "url": ""
    }
  ]
}

常见问题解决

1. API密钥权限不足

1
2
3
4
5
6
7
# 错误信息
[ERROR] API请求失败: /api/user (退出码: 22)

# 解决方法
# 1. 检查API密钥是否正确
# 2. 确保API密钥有足够权限(Admin或Editor)
# 3. 重新生成API密钥

2. 网络连接问题

1
2
3
4
5
6
7
8
# 错误信息
[ERROR] 连接失败! 请检查URL和API密钥

# 解决方法
# 1. 检查Grafana URL是否正确
# 2. 确保Grafana服务正在运行
# 3. 检查网络连接
curl -I http://localhost:3000

3. 依赖缺失

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 错误信息
[ERROR] 缺少必要依赖: jq

# 解决方法
# macOS
brew install jq curl

# Ubuntu/Debian
sudo apt-get install jq curl

# CentOS/RHEL
sudo yum install jq curl

4. 文件权限问题

1
2
3
4
5
# 错误信息
bash: ./export-dashboards.sh: Permission denied

# 解决方法
chmod +x export-dashboards.sh

自动化和定时任务

1. 创建定时备份

1
2
3
4
5
# 编辑crontab
crontab -e

# 添加定时任务(每天凌晨2点备份)
0 2 * * * /path/to/export-dashboards.sh --api-key $GRAFANA_API_KEY --output /backup/grafana

2. 集成到CI/CD

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# .github/workflows/grafana-backup.yml
name: Grafana Dashboard Backup

on:
  schedule:
    - cron: '0 2 * * *'  # 每天凌晨2点
  workflow_dispatch:

jobs:
  backup:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y jq curl
      
      - name: Export Grafana dashboards
        env:
          GRAFANA_API_KEY: ${{ secrets.GRAFANA_API_KEY }}
          GRAFANA_URL: ${{ secrets.GRAFANA_URL }}
        run: |
          chmod +x export-dashboards.sh
          ./export-dashboards.sh --output ./backup
      
      - name: Upload backup
        uses: actions/upload-artifact@v3
        with:
          name: grafana-backup
          path: ./backup

3. Docker化部署

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Dockerfile
FROM alpine:latest

RUN apk add --no-cache bash curl jq python3 py3-pip
RUN pip3 install requests

WORKDIR /app
COPY export-dashboards.sh export-grafana-dashboards.py ./
RUN chmod +x export-dashboards.sh export-grafana-dashboards.py

VOLUME ["/backup"]

CMD ["./export-dashboards.sh", "--output", "/backup"]
1
2
3
4
5
6
7
# 构建和运行
docker build -t grafana-exporter .

docker run -v $(pwd)/backup:/backup \
           -e GRAFANA_URL=http://grafana.example.com \
           -e GRAFANA_API_KEY=your-api-key \
           grafana-exporter

最佳实践

  1. 定期备份: 建议每天自动备份仪表板
  2. 版本控制: 将导出的JSON文件纳入Git管理
  3. 权限管理: 使用专门的API密钥,定期轮换
  4. 监控告警: 监控备份任务的执行状态
  5. 测试恢复: 定期测试仪表板恢复流程
  6. 文档记录: 记录重要仪表板的用途和配置说明
0%