Dashboards as Code
A dashboard built by clicking lives only in one Grafana's database: no review, no history, no way to give staging and production the same one, and gone when someone deletes it. Dashboards as code keeps them in Git and deploys them like anything else.
The options
| Approach | How | Good for |
|---|---|---|
| JSON in Git + file provisioning | export the dashboard JSON, commit it, Grafana loads a folder of JSON files at startup | simple, works everywhere |
| Generated JSON | write code that emits the JSON: Grafana's Foundation SDK (Go, TypeScript, Python, Java, PHP), Grafonnet (Jsonnet), or a small script of your own | many similar dashboards, shared panel libraries |
| Terraform | grafana_dashboard, grafana_folder, grafana_data_source resources in the Grafana provider |
teams already managing everything with Terraform (Terraform course) |
| Git Sync | Grafana itself commits dashboard changes to a Git repository and opens pull requests (GA in Grafana 13) | letting people edit in the UI while Git stays the source of truth |
| Kubernetes | dashboards in ConfigMaps picked up by a sidecar (kube-prometheus-stack's grafana_dashboard: "1" label) or the Grafana Operator's GrafanaDashboard CRD |
GitOps clusters (GitOps) |
Whatever the tool, the rules are the same: stable uids, data sources referenced by uid or by a ${datasource} variable, no environment-specific values baked in, and a review before merge.
The JSON model
Grafana 12 introduced a new dashboard schema (v2, behind "dynamic dashboards", the default in Grafana 13); Grafana migrates classic JSON when it loads it, so the classic model below still imports everywhere. Its key fields:
{
"uid": "linkly-red",
"title": "linkly / RED",
"tags": ["linkly", "red"],
"timezone": "utc",
"schemaVersion": 42,
"time": { "from": "now-6h", "to": "now" },
"templating": { "list": [ { "name": "env", "type": "query", "query": "label_values(up{job=\"linkly\"}, env)" } ] },
"panels": [ { "id": 1, "type": "timeseries", "title": "…", "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 }, "targets": [] } ]
}gridPos places the panel on a 24-column grid. Panel ids must be unique within the dashboard.
Generating a dashboard
A short generator is often all a team needs: one function per panel kind, a loop over the RED signals. This session generates linkly's RED dashboard with Python, then lints it with jq the way a CI job would:
mkdir -p dashboards && cat > gen_dashboard.py <<'PY'
import json
DS = {"type": "prometheus", "uid": "${datasource}"}
SEL = 'job="linkly", env="$env"'
def timeseries(pid, title, expr, legend, unit, x, y):
return {"id": pid, "type": "timeseries", "title": title, "datasource": DS,
"gridPos": {"x": x, "y": y, "w": 12, "h": 8},
"fieldConfig": {"defaults": {"unit": unit}, "overrides": []},
"targets": [{"refId": "A", "expr": expr, "legendFormat": legend}]}
panels = [
timeseries(1, "Rate: requests / s by route",
f'sum by (route) (rate(http_requests_total{{{SEL}}}[$__rate_interval]))', "{{route}}", "reqps", 0, 0),
timeseries(2, "Errors: 5xx ratio",
f'sum(rate(http_requests_total{{{SEL}, code=~"5.."}}[$__rate_interval])) / sum(rate(http_requests_total{{{SEL}}}[$__rate_interval]))',
"5xx", "percentunit", 12, 0),
timeseries(3, "Duration: p99 by route",
f'histogram_quantile(0.99, sum by (route, le) (rate(http_request_duration_seconds_bucket{{{SEL}}}[$__rate_interval])))',
"{{route}}", "s", 0, 8),
timeseries(4, "Saturation: DB pool in use",
f'sum(linkly_db_connections_in_use{{{SEL}}}) / sum(linkly_db_connections_max{{{SEL}}})', "pool", "percentunit", 12, 8),
]
dashboard = {
"uid": "linkly-red", "title": "linkly / RED", "tags": ["linkly"], "timezone": "utc",
"schemaVersion": 42, "time": {"from": "now-6h", "to": "now"}, "refresh": "1m",
"templating": {"list": [
{"name": "datasource", "type": "datasource", "query": "prometheus"},
{"name": "env", "type": "query", "datasource": DS, "query": 'label_values(up{job="linkly"}, env)', "refresh": 2},
]},
"panels": panels,
}
with open("dashboards/linkly-red.json", "w") as f:
json.dump(dashboard, f, indent=2, sort_keys=True)
f.write("\n")
PY
python3 gen_dashboard.py
jq -r '.panels[] | "\(.id) \(.gridPos.x),\(.gridPos.y) \(.title)"' dashboards/linkly-red.json
cat > lint.jq <<'JQ'
# problems in a classic dashboard JSON, one per line
[ (if (.uid // "") == "" then "dashboard has no uid" else empty end),
(.panels | group_by(.id)[] | select(length > 1) | "duplicate panel id \(.[0].id)"),
(.panels[] | .title as $t | .targets[]?.expr
| select(test("rate\\(") and (test("\\$__rate_interval") | not))
| "\($t): rate() without $__rate_interval"),
(.panels[] | select(.datasource.uid | test("^\\quot;) | not) | "\(.title): hard-coded data source uid")
] | .[]
JQ
echo "--- lint:"
jq -r -f lint.jq dashboards/linkly-red.json
echo "--- lint a hand-edited copy:"
jq '.panels[0].targets[0].expr |= sub("\\$__rate_interval"; "1m") | .panels[1].id = 1 | .panels[2].datasource.uid = "P1809F7CD0C75ACF3"' \
dashboards/linkly-red.json > broken.json
jq -r -f lint.jq broken.json1 0,0 Rate: requests / s by route
2 12,0 Errors: 5xx ratio
3 0,8 Duration: p99 by route
4 12,8 Saturation: DB pool in use
--- lint:
--- lint a hand-edited copy:
duplicate panel id 1
Rate: requests / s by route: rate() without $__rate_interval
Duration: p99 by route: hard-coded data source uid
The generated file lints clean (the empty section). The generator gives every dashboard the same data-source variable, environment selector and layout; the lint catches the mistakes that creep in when someone exports a dashboard from the UI and commits it (the copy has a hard-coded data-source uid, a duplicated id and a fixed [1m] window). Commit the generated JSON too, so reviews show the real change.
Provisioning the files
Grafana loads every JSON file in a folder through a dashboard provider:
# provisioning/dashboards/linkly.yaml
apiVersion: 1
providers:
- name: linkly
folder: linkly # Grafana folder to put them in
type: file
disableDeletion: true
allowUiUpdates: false # UI edits can't be saved: change the code instead
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards/linkly
foldersFromFilesStructure: falseWith allowUiUpdates: false, people can still edit and explore, but "Save" tells them the dashboard is provisioned; they export the JSON and open a pull request.
The same with Terraform
resource "grafana_folder" "linkly" {
title = "linkly"
}
resource "grafana_dashboard" "linkly_red" {
folder = grafana_folder.linkly.uid
config_json = file("${path.module}/dashboards/linkly-red.json")
overwrite = true
}Terraform also manages data sources, contact points, notification policies and alert rules (grafana_contact_point, grafana_notification_policy, grafana_rule_group), which is how many teams keep a whole Grafana (including Grafana Cloud stacks) reproducible.
Test yourself
Why reference data sources through a ${datasource} variable or a fixed uid in dashboard JSON?
- It's faster
- Exported dashboards otherwise contain an environment-specific generated uid and break elsewhere
- Grafana requires variables
- To enable alerting
What does allowUiUpdates: false do for provisioned dashboards?
- Hides them
- Prevents saving UI edits over the provisioned version, so changes go through code
- Makes them read-only for queries
- Disables variables
Which Grafana 13 feature commits dashboard changes made in the UI to a Git repository?
- Explore
- Git Sync
- Provisioning
- Library panels