Grafanalib

0.7.1 · active · verified Thu Apr 16

Grafanalib is a Python library for programmatically building Grafana dashboards. It allows users to define dashboards, panels, and targets in Python code, generating the corresponding Grafana JSON model. As of version 0.7.1, it focuses on adding support for newer Grafana features, with releases occurring periodically to keep up with Grafana updates and dependency bumps.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic Grafana dashboard with a single row and a CPU Usage graph panel. It uses a Prometheus datasource (replace 'my_prometheus_datasource' with your actual datasource name). The output is a JSON string which can be saved and imported into Grafana.

import json
from grafanalib.core import Dashboard, Graph, Row, OPS_FORMAT, SEC_FORMAT, YAxes, YAxis

dashboard = Dashboard(
    title="My First Grafana Dashboard",
    description="A simple dashboard created with grafanalib",
    rows=[
        Row(
            panels=[
                Graph(
                    title="CPU Usage",
                    dataSource='my_prometheus_datasource',
                    targets=[
                        {
                            "expr": 'node_cpu_seconds_total{mode="idle"}',
                            "legendFormat": "idle",
                            "refId": "A"
                        }
                    ],
                    yAxes=YAxes([YAxis(format=OPS_FORMAT), YAxis(format=SEC_FORMAT)]),
                )
            ]
        )
    ],
    id=None
).to_json_data(indent=2)

print(dashboard)

# To upload this dashboard to Grafana:
# 1. Save the output to a file (e.g., my_dashboard.json)
# 2. Use the Grafana UI to import the JSON
# 3. Alternatively, use grafanalib.client or another script to POST to Grafana API

view raw JSON →