Grafana: Dashboards as Code

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Grafana 13.3.x. Tested with Grafana Enterprise 13.3.0 in the hands-on lab: the lab’s dashboard provider and dashboard file load; the Terraform blocks pass terraform validate with provider 4.54.0 apart from variables and files they refer to.

A dashboard built in the browser is stored in the Grafana database, and nothing else knows it exists: it cannot be reviewed, it cannot be rebuilt in a second environment, and it disappears with the database. Grafana offers several ways to keep the definition in text instead, in Git, and to load it from there. This page covers every one of them for dashboards and folders: file provisioning, Git Sync, the Foundation SDK, Terraform, the Grafana Operator, the gcx command-line tool and the /apis HTTP API. The running example is the lab dashboard "Bookshelf service health" (uid bookshelf-service-health) in the folder bookshelf, which is built by hand on Building Dashboards.

The tool-neutral argument (why Git, drift, secrets, a plan-then-apply pipeline) and the Kibana comparison are on Observability as Code; this page does not repeat them. Alert rules, contact points and notification policies have their own page, Provisioning Alerting Resources. The JSON that all of these tools carry is explained on Library Panels, JSON Model and Versions, and the Terraform fundamentals are in the Terraform section of this site (State, CI/CD and Automation).

Source: Grafana docs — Manage Grafana as code. The page states that Grafana 12 introduced new versioned APIs and official tooling, and that gcx, Git Sync and the Foundation SDK are built on them. It also states that most of the tools can be used with one another.

The as-code paths into Grafana

Every option ends in the same place: a dashboard stored in Grafana. They differ in where the definition lives, who triggers the load, and whether a change made in the Grafana UI can travel back.

flowchart LR SDK["Foundation SDK program (Go, TypeScript, Python, PHP, Java)"] -->|"generates JSON"| REPO HAND["Dashboard JSON edited by hand or exported"] --> REPO["Git repository"] REPO -->|"file path on the Grafana host"| PROV["File provisioning"] REPO <-->|"poll 60 s or webhook, branch and pull request"| GS["Git Sync"] REPO -->|"pipeline: terraform apply"| TF["Terraform provider"] REPO -->|"pipeline: gcx resources push"| CLI["gcx CLI"] REPO -->|"Argo CD sync of custom resources"| OP["Grafana Operator in Kubernetes"] PROV --> G["Grafana: dashboards and folders"] GS --> G TF -->|"/apis"| G CLI -->|"/apis"| G OP -->|"HTTP API"| G G -.->|"UI edit saved as commit or pull request"| GS

Only Git Sync has the return arrow: it is the one tool in which Grafana itself writes to the repository. With every other path the files are the source of truth and the UI is read-only for the provisioned dashboards, or any UI edit is overwritten by the next apply.

Path Use it when Direction Watch out for

Classic file provisioning (provisioning/dashboards)

Self-managed Grafana (Docker, Kubernetes, VM), files shipped with the image or a volume.

Files to Grafana.

Not available in Grafana Cloud. The files must reach the Grafana host.

On-prem file provisioning (Repository of type local)

Grafana 12 or later, OSS or Enterprise, when you want the UI to show the files as provisioned and manage them as a repository resource.

Files to Grafana.

Dashboards only, up to 10 connections, not Cloud.

Git Sync

Teams that edit in the UI and want every change to be a commit or a pull request, or edit in Git and want Grafana to follow.

Both ways.

Dashboards and folders only (no alert rules, data sources or panels); Grafana 13.0.0 itself has a migration bug, use 13.0.1 or later.

Foundation SDK

Dashboards that are generated (many services, many environments, repeated rows) and need compile-time checking.

Code to JSON; you deploy the JSON.

It generates, it does not deploy. Pair it with gcx, the API, Terraform or Git Sync.

Terraform provider

One tool and one plan for folders, data sources, dashboards and alerting, Cloud or self-managed.

Code to Grafana.

State, secrets and drift; dashboard JSON inside Terraform is verbose; pick the resource that matches the dashboard API version.

Grafana Operator

A Kubernetes cluster that already uses GitOps (Argo CD or Flux).

Custom resources to Grafana.

A community project, not commercially supported by Grafana.

gcx

A pipeline or a developer shell that pushes resources, previews generated dashboards, or sets Git Sync up as code.

Local files to Grafana.

Needs a service account token. The older grafanactl is deprecated.

/apis HTTP API

Your own scripts and tools in any language.

Both ways, by request.

You write the diffing, ordering and retry logic. The legacy /api is deprecated in favour of /apis.

A rule of thumb that fits the Bookshelf lab: provisioning files for the lab itself (they start with the container), Git Sync when people edit dashboards in the UI, Foundation SDK plus a pipeline when a generator produces the dashboards, and Terraform when the same pipeline already owns the folders, data sources and alert rules. Do not point two tools at the same dashboard: the second apply overwrites the first, and with Git Sync a dashboard owned by another tool is rejected or overwritten (see What can go wrong).

Classic file provisioning

Grafana reads YAML files from provisioning/dashboards at startup. Each file lists one or more providers; a provider says where the dashboard JSON files are, which folder they go to, and how often Grafana looks for changes. The dashboard JSON itself stays in separate files, which is why the provider file is short.

# provisioning/dashboards/bookshelf.yaml
apiVersion: 1

providers:
  - name: bookshelf
    orgId: 1
    folder: bookshelf
    folderUid: bookshelf
    type: file
    disableDeletion: true
    updateIntervalSeconds: 30
    allowUiUpdates: false
    options:
      path: /var/lib/grafana/dashboards/bookshelf

The directory with the JSON is a volume of the lab Compose file, next to the provider directory:

services:
  grafana:
    image: grafana/grafana-enterprise:13.3.0
    volumes:
      - ./provisioning/dashboards:/etc/grafana/provisioning/dashboards:ro
      - ./dashboards:/var/lib/grafana/dashboards/bookshelf:ro

The meaning of each provider option, from the official page:

Option Effect

name

Unique name of the provider (required).

orgId

Organization to load the dashboards into; default 1.

folder, folderUid

Folder the dashboards are placed in. If folder is omitted the dashboards are placed at the root level. folderUid is generated if omitted, so set it when other tools (alert rules, permissions) must refer to the folder.

type

Provider type; file is the default.

disableDeletion

When true, removing the provisioning source does not delete the dashboards from the database. When false, removing the source deletes them.

updateIntervalSeconds

How often Grafana scans for changes. Above 10 seconds it polls at that interval; at 10 or less it watches the file system for events, which some Docker bind mounts and network file systems do not deliver. Set a value above 10 to force polling when changes are missed.

allowUiUpdates

false: saving a provisioned dashboard from the UI shows "Cannot save provisioned dashboard". true: UI saves are persisted in the database, but a later change of the file overwrites them, and Grafana ignores the JSON version property.

options.path

Directory with the dashboard files (required for the file type).

options.foldersFromFilesStructure

Creates Grafana folders that match the directory structure on disk (up to four levels). It requires folder and folderUid to be unset, and files at the root of path appear at the root level.

Three details matter in practice. First, the uid inside the dashboard JSON decides which dashboard is updated, so a fixed uid (bookshelf-service-health) keeps links, alert annotations and dashboardUID references stable across environments; avoid reusing a title within a folder or a uid within an instance. Second, $VAR_NAME and ${VAR_NAME} are interpolated in provisioning configuration values (for example a folder name taken from an environment variable), but not inside the dashboard definition files. Third, in Grafana 13 a dashboard in the V2 schema or a dynamic dashboard must be written in the Kubernetes resource format (apiVersion: dashboard.grafana.app/v1 and so on) rather than as a plain JSON model.

To get the first JSON file, export the dashboard from the UI or read it with the /apis call shown below; the "Export" and "Save to file" options are on Sharing and Reporting.

Reference: Grafana docs — Provision Grafana (section "Dashboards"). The server-side settings for the provisioning directory are on Installation and Configuration.

On-prem file provisioning

Grafana 12 and later also offer a second, repository-style file mechanism for self-managed OSS and Enterprise. It is the same Repository resource that Git Sync uses, with the type set to local. The dashboards and folders it loads are labelled provisioned in the UI, appear in a provisioned folder, and can be changed only by editing the files. It handles dashboards only, it is not available in Grafana Cloud, and it does not replace classic provisioning (the official setup page itself recommends foldersFromFilesStructure for production systems). Up to 10 connections can be configured.

Grafana first has to be told which directories may be used. In the [paths] section of grafana.ini or custom.ini, set permitted_provisioning_paths to the allowed paths separated by a pipe character, with no empty entries and no trailing pipe (the default values are devenv/dev-dashboards and conf/provisioning). A repository path must begin with one of them, so the path of the example below (/etc/grafana/provisioning/dashboards-local) needs /etc/grafana/provisioning/ in that list. The provisioning feature toggle is on by default from Grafana 13 on, so no toggle is needed.

# repository.yaml
apiVersion: provisioning.grafana.app/v0alpha1
kind: Repository
metadata:
  name: bookshelf-local
spec:
  title: Bookshelf local dashboards
  type: local
  local:
    path: /etc/grafana/provisioning/dashboards-local
  sync:
    enabled: true
    intervalSeconds: 60
    target: folder
  workflows:
    - write
gcx resources push --path ./repository-resources
gcx resources get repositories

spec.sync.target is folder (the default: one wrapper folder named after the repository) or folderless (resources at the top level). An empty spec.workflows makes the mount read-only. The same repository can be configured in the UI under Administration > Provisioning > Configure file provisioning, where the setup also offers to migrate existing unmanaged dashboards. Full instance sync prevents creating new alerts or library panels, so use folder sync if you need them.

Source: Grafana docs — On-prem file provisioning and Set up file provisioning (sections "Configure permitted paths" and "Set up file provisioning as code").

Git Sync

Git Sync stores dashboards as JSON files in a Git repository and keeps the repository and Grafana in step in both directions. A dashboard edited in the UI is saved as a commit or a pull request; a file changed in Git (by a person, a generator or a pull-request merge) is pulled into Grafana. It became generally available with Grafana 13.0 for Grafana Cloud and for self-managed Grafana.

Grafana 13.0.0 contains a migration bug: a Git Sync early adopter who upgrades from 12.x.x may lose or revert dashboards and folders, and upgrading from 13.0.0 to 13.0.1 does not recover the lost data. Use 13.0.1 or later; if 13.0.0 is already running, restore the database first and then upgrade. The lab uses 13.3.x.

Source: What’s new in Grafana 13.0 (Git Sync generally available; the warning about the 13.0.0 migration bug) and Git Sync.

Concepts

  • A connection resource holds the authentication between Grafana and a Git provider, for example a GitHub App. It is not needed with a personal access token. One connection can serve several repositories.

  • A repository resource describes the repository, branch, path and sync behaviour; each one is a bidirectional sync between one Grafana instance and one location in Git.

  • Provisioned resources are the ones managed by Git Sync. Only files inside the configured path are synced; everything else in the repository is ignored.

  • Folder sync (the default target) creates one Grafana folder named after the repository and turns sub-directories into sub-folders. Folderless sync puts resources at the top level, and several folderless repositories can coexist.

  • Each folder in the repository can contain a _folder.json that stores the folder’s stable uid and display name, so the folder keeps its identity and permissions when moved or renamed. The dashboard title comes from the JSON, not from the file name.

Prerequisites and limits

Git Sync needs administration rights in the Grafana organization. The provisioning feature toggle is enabled by default in Grafana Cloud and, from Grafana 13, in OSS and Enterprise. Providers and their availability:

Provider Available in Authentication

Pure Git

Cloud, OSS, Enterprise

Personal access token or OAuth App

GitHub

Cloud, OSS, Enterprise

Personal access token, GitHub App or OAuth App

GitHub Enterprise

Cloud, Enterprise

Personal access token, GitHub App or OAuth App

GitLab

Cloud, Enterprise

Personal access token or OAuth App

Bitbucket

Cloud, Enterprise

API token with scopes or OAuth App

Pure Git works with any Git server that supports the Smart HTTP protocol version 2 (SSH is not supported, which excludes Azure DevOps), but webhook-driven sync, pull-request comments and deep links need an enhanced integration such as the GitHub one. In a self-managed Grafana the providers and OAuth connection types are switched on in the [provisioning] section, and hosts that resolve to private addresses are blocked unless they are listed in allowed_git_urls:

[provisioning]
repository_types = "git|github|bitbucket|gitlab|local"
allowed_git_urls = git.internal.example.com, ghe.example.com:8443

Only list trusted hosts in allowed_git_urls, because they receive the Git token. A GitHub App needs these repository permissions: Administration (read-only), Contents (read and write), Metadata (read-only), Pull requests (read and write) and Webhooks (read and write). An OAuth connection acts as the user who authorized it and can reach every repository that user can reach, so use a dedicated account for it.

The limits that shape a design:

  • Only dashboards and folders are supported. Alert rules, data sources and panels are not; manage alerting with Provisioning Alerting Resources.

  • Nested folders go four levels deep.

  • Self-managed OSS and Enterprise default to 10 repositories and no limit on resources per repository (max_repositories and max_resources_per_repository in [provisioning]); Cloud Free allows 1 repository with 20 resources, and other Cloud plans 10 repositories with 1,000 resources each. Keep a connection under about 1,000 resources, and split larger estates into several connections that point to different folder paths with folderless sync.

  • Restoring a deleted dashboard from the UI is not possible; revert the deletion in Git.

  • Enabling Git Sync can raise database load, especially with many folders: try it outside production first.

Set it up as code

The UI wizard (Administration > General > Provisioning) is the quickest start; the same configuration is two small resources, which is what a team keeps in a repository of its own. First the repository resource, here with a personal access token for the Bookshelf dashboards repository:

# repository.yaml
apiVersion: provisioning.grafana.app/v0alpha1
kind: Repository
metadata:
  name: bookshelf-dashboards
spec:
  title: Bookshelf dashboards
  type: github
  sync:
    enabled: true
    intervalSeconds: 60
    target: folder
  workflows:
    - write
    - branch
  github:
    url: https://github.com/example/bookshelf-dashboards
    branch: main
    path: grafana/
secure:
  token:
    create: <GIT_PAT>

workflows decides what Grafana may do with the repository: write allows direct commits, branch requires a branch (and so a pull request), and an empty list makes the repository read-only. To use a GitHub App instead of a token, create a Connection resource (kind: Connection, spec.type: github, with spec.github.appID, spec.github.installationID and the private key under secure.privateKey) and replace secure.token with spec.connection.name. Then push the files and check:

gcx resources push --path ./git-sync
gcx resources get repositories
gcx resources get repository/bookshelf-dashboards -o yaml

The same repository can be created with Terraform (Terraform 1.11 or later, provider grafana/grafana at least 4.28.1), through the grafana_apps_provisioning_repository_v0alpha1 resource, whose spec block has the same fields (type, workflows, a sync block with enabled, target and interval_seconds, and a github block with url, branch and path):

resource "grafana_apps_provisioning_repository_v0alpha1" "bookshelf" {
  metadata {
    uid = "bookshelf-dashboards"
  }

  spec {
    title     = "Bookshelf dashboards"
    type      = "github"
    workflows = ["write", "branch"]

    sync {
      enabled          = true
      target           = "folder"
      interval_seconds = 60
    }

    github {
      url    = "https://github.com/example/bookshelf-dashboards"
      branch = "main"
      path   = "grafana"
    }
  }

  secure {
    token = {
      create = var.git_token
    }
  }
  secure_version = 1
}

The resource and the API group use the v0alpha1 version, so confirm its status in the release notes before basing a production pipeline on it.

Source: Set up Git Sync as code and Set up Git Sync with Terraform (the Terraform page uses a placeholder for the token; var.git_token stands for a sensitive variable).

The pull-request workflow

With workflows containing branch, editing a provisioned dashboard follows the same review path as code:

  1. Open the dashboard, select Edit, change it and select Save dashboard.

  2. In the Provisioned dashboard panel choose the Branch, Repository folder, Filename and Comment; the Changes tab shows the diff against the saved resource.

  3. Select Save, then Open a pull request in GitHub and merge it in the normal way.

While the change sits on a branch, Grafana shows a preview banner (created, updated, deleted or moved) to the person who made it, with Open a pull request or View pull request; other users keep seeing the configured branch until the merge. If the branch has been deleted the banner offers Save to a new branch or View the current version. Deleting a dashboard works the same way, from the dashboard settings, and deleting the file in the repository removes the dashboard after the next sync. Requiring approval for pull requests and protecting the main branch is configured in the Git provider; see Configure Git repository protection.

Grafana pulls changes by polling every 60 seconds by default (changeable in the repository settings). With a webhook the notification arrives almost immediately; webhooks need an enhanced integration and a Grafana that the Git server can reach. The Pull button on the repository page forces a sync and overwrites dashboards with the same uid.

The Foundation SDK

The Grafana Foundation SDK defines dashboards and other resources as strongly typed code in Go, TypeScript, Python, PHP or Java. Typos, wrong units and invalid structures fail at compile time, and ordinary code (functions, loops, libraries) removes the copy-and-paste that makes large dashboard JSON hard to maintain. The SDK uses a builder pattern: a DashboardBuilder collects panels, each panel has its own builder (stat, timeseries, …​), each query has a data-source specific DataqueryBuilder, and build() returns the dashboard object, which serializes to the JSON model. The SDK needs a Grafana of version 10.0 or later and a language environment. It replaces Grafonnet, which is not officially supported, and Grizzly, which has been removed.

Install it with npm install @grafana/grafana-foundation-sdk (TypeScript) or go get github.com/grafana/grafana-foundation-sdk/go@latest (Go); the Python, PHP and Java packages are described in the SDK documentation. The program below generates the first two panels of "Bookshelf service health" for the lab’s Prometheus data source and prints a dashboard resource in the Kubernetes-style envelope that gcx and the /apis API accept:

// scripts/generate-dashboard.ts
import * as common from '@grafana/grafana-foundation-sdk/common';
import * as dashboard from '@grafana/grafana-foundation-sdk/dashboard';
import * as prometheus from '@grafana/grafana-foundation-sdk/prometheus';
import * as resource from '@grafana/grafana-foundation-sdk/resource';
import * as stat from '@grafana/grafana-foundation-sdk/stat';
import * as timeseries from '@grafana/grafana-foundation-sdk/timeseries';

const prom = { type: 'prometheus', uid: 'prometheus' };
const sel = 'application="bookshelf"';

const ratio5xx =
  `sum(rate(http_server_requests_seconds_count{${sel},status=~"5.."}[$__rate_interval]))` +
  ` / sum(rate(http_server_requests_seconds_count{${sel}}[$__rate_interval]))`;

const builder = new dashboard.DashboardBuilder('Bookshelf service health')
  .uid('bookshelf-service-health')
  .tags(['bookshelf', 'generated'])
  .refresh('30s')
  .time({ from: 'now-1h', to: 'now' })
  .withPanel(
    new stat.PanelBuilder()
      .title('5xx ratio')
      .datasource(prom)
      .unit('percentunit')
      .reduceOptions(new common.ReduceDataOptionsBuilder().calcs(['lastNotNull']).fields('/.*/'))
      .withTarget(new prometheus.DataqueryBuilder().expr(ratio5xx))
  )
  .withPanel(
    new timeseries.PanelBuilder()
      .title('Request rate by route')
      .datasource(prom)
      .unit('reqps')
      .withTarget(
        new prometheus.DataqueryBuilder()
          .expr(`sum by (uri) (rate(http_server_requests_seconds_count{${sel}}[$__rate_interval]))`)
          .legendFormat('{{uri}}')
      )
  );

const manifest = new resource.ManifestBuilder()
  .apiVersion('dashboard.grafana.app/v1')
  .kind('Dashboard')
  .metadata(new resource.MetadataBuilder().name('bookshelf-service-health'))
  .spec(builder.build());

console.log(JSON.stringify(manifest.build(), null, 2));

The sel constant keeps the application="bookshelf" label in one place, which is exactly the kind of reuse that the generated JSON lacks. The three panels that are not shown (p95 latency, no-data state timeline and the logs panel) are further withPanel calls of the same shape. The program prints the envelope with both panels and the default settings the SDK fills in (a schemaVersion, the time zone, the tooltip mode); those defaults can change between SDK versions, so review the diff of the generated file when the SDK is upgraded.

An equivalent Go program uses dashboard.NewDashboardBuilder, timeseries.NewPanelBuilder and prometheus.NewDataqueryBuilder().Expr(...).LegendFormat(...), and builds the same envelope with the resource package; the SDK repository has complete examples for several languages, including a RED-method dashboard and alert rules (examples folder).

The generated JSON is deployed in one of the ways the documentation lists: the dashboard import feature, the Grafana HTTP API, the Grafana CLI (gcx) or Git Sync (commit the generated file into the synced repository). In a CI job the sequence is generate, then push:

npx tsx scripts/generate-dashboard.ts > dashboard.json
gcx resources push dashboards --path ./dashboard.json

The official CI/CD example (GitHub Actions) installs gcx from its release, runs the generator on every push to main, and pushes with the environment variables GRAFANA_SERVER, GRAFANA_STACK_ID and GRAFANA_TOKEN (a service account token). Keep the token in the CI secret store, never in the repository.

gcx, the Grafana CLI

gcx is the command-line tool for managing Grafana and Grafana Cloud from a terminal and from agentic coding tools. It works with Grafana Cloud, Enterprise and OSS, handles authentication and multiple environments (contexts), and covers querying, inspecting and managing resources and automating workflows as code. It is the tool the Git Sync, file-provisioning and Foundation SDK pages use to push resources. The older grafanactl CLI is marked deprecated in the documentation, and Grizzly was removed, so do not start new work on either.

Install it with the script or with Homebrew:

curl -fsSL https://raw.githubusercontent.com/grafana/gcx/main/scripts/install.sh | sh
brew install gcx

The documented dashboards-as-code workflow has four steps. It needs the kubernetesDashboards = true toggle in [feature_toggles], and gcx dev serve needs a service account token rather than OAuth:

gcx config use-context dev
gcx dev serve --script 'go run scripts/generate-dashboard.go' --watch './scripts'
go run scripts/generate-dashboard.go --generate-resource-manifests --output './resources'
gcx resources push -p ./resources/

The first command selects the target environment, the second previews the generated dashboard locally and re-runs the script when files under scripts change, the third writes manifest files, and the last pushes them to Grafana. The gcx resources get, edit and delete commands are shown above for repositories.

Source: Grafana docs — Grafana CLI tools, gcx installation and Manage dashboards as code with gcx. The CLI reference lists the commands and flags of the latest stable release.

The /apis HTTP API

Since Grafana 13 the Kubernetes-style /apis API is the preferred way to read and write dashboards; the legacy /api paths are deprecated in favour of it. The URL has the form /apis/<GROUP>/<VERSION>/namespaces/<NAMESPACE>/<RESOURCE>[/<NAME>]: the name is part of the path for get, update and delete, and omitted for list and create. The path uses metadata.name, which for the lab dashboard is its uid. Versions follow Kubernetes conventions: v1alpha1 is experimental and off by default, v1beta1 is more stable and off by default, and v1 is generally available and on. In a self-managed Grafana the namespace is default for organization 1 and org-<ORG_ID> for others; in Grafana Cloud it is stacks-<STACK_ID>. Dashboards live in the group dashboard.grafana.app.

Read the lab dashboard (this is also the quickest way to export JSON for provisioning files):

curl -s -H "Authorization: Bearer $GRAFANA_TOKEN" \
  http://localhost:3000/apis/dashboard.grafana.app/v1/namespaces/default/dashboards/bookshelf-service-health

Create it in the folder bookshelf. The folder is set with the grafana.app/folder annotation, the name is the dashboard uid, and the response is 201 on success or 409 if a dashboard with that name already exists:

curl -s -X POST -H "Authorization: Bearer $GRAFANA_TOKEN" -H "Content-Type: application/json" \
  http://localhost:3000/apis/dashboard.grafana.app/v1/namespaces/default/dashboards \
  -d '{
    "metadata": {
      "name": "bookshelf-service-health",
      "annotations": { "grafana.app/folder": "bookshelf" }
    },
    "spec": {
      "title": "Bookshelf service health",
      "schemaVersion": 41,
      "panels": [],
      "time": { "from": "now-1h", "to": "now" }
    }
  }'

The token belongs to a service account with dashboards:create on the folder (or dashboards:write), such as the lab’s ci-provisioner (see Users, Teams and Permissions). The spec is the dashboard model, so the file produced by the SDK or an export fits here. The URL scheme is also introduced on Installation and Configuration.

Source: Grafana docs — APIs (URL structure, versions, namespaces) and Dashboard API — Create Dashboard.

Terraform

The grafana/grafana provider manages more Grafana resources than the other as-code tools: dashboards, data sources, plugins, alerts, collectors, synthetic monitoring and identity and access, for Cloud and for self-managed Grafana. The fundamentals (providers, credentials from GRAFANA_URL and GRAFANA_AUTH, service accounts instead of API keys, provenance and the single-owner rule) are on Observability as Code, and the alerting resources are on Provisioning Alerting Resources. For dashboards, the resource to use depends on the Grafana version and on the dashboard API version:

  • grafana_dashboard is the legacy resource. It takes the complete dashboard model as config_json, an optional folder (uid) and overwrite. On Grafana 12 or earlier it is the recommended resource; on Grafana 13 and later, with a Kubernetes-style definition, config_json must hold the full document (apiVersion, kind, metadata and spec), and the provider documentation says to use the resource that matches the dashboard’s API version instead.

  • grafana_apps_dashboard_dashboard_v1beta1 (and the V2 variants documented next to it) manages dashboards through the new APIs. Its metadata block takes the uid and an optional folder_uid; spec.json holds the dashboard JSON; an options block has overwrite and allow_ui_updates (by default a Terraform-managed resource cannot be edited in the UI).

resource "grafana_folder" "bookshelf" {
  title = "bookshelf"
  uid   = "bookshelf"
}

resource "grafana_apps_dashboard_dashboard_v1beta1" "service_health" {
  metadata {
    uid        = "bookshelf-service-health"
    folder_uid = grafana_folder.bookshelf.uid
  }

  spec {
    title = "Bookshelf service health"
    json  = file("${path.module}/dashboards/bookshelf-service-health.json")
  }
}

Here dashboards/bookshelf-service-health.json holds the dashboard model (the spec of the SDK output or of an export). terraform plan then shows a dashboard change as a diff of the file, and terraform apply writes it; the dashboard is read-only in the UI because Terraform owns it.

Reference: Grafana docs — Grafana Terraform provider (overview and guides, including managing dashboards with GitHub Actions), grafana_dashboard, grafana_apps_dashboard_dashboard_v1beta1 and grafana_folder.

The Grafana Operator and Argo CD

The Grafana Operator is a Kubernetes operator that keeps custom resources and a Grafana instance in step; its support is mainly for dashboards, folders, alerts and data sources. It can install and run Grafana itself, or manage an external instance such as the lab Grafana or a Grafana Cloud stack. It is a community project and is not commercially supported by Grafana, which matters when you choose it for production. Install it with Helm:

helm repo add grafana https://grafana.github.io/helm-charts
helm upgrade -i grafana-operator grafana/grafana-operator

Three custom resources are enough for the Bookshelf dashboard. A Grafana resource describes the target instance and the credentials, using a service account token from a Secret; the label on it is what dashboards select with instanceSelector:

apiVersion: grafana.integreatly.org/v1beta1
kind: Grafana
metadata:
  name: bookshelf-grafana
  labels:
    dashboards: bookshelf-grafana
spec:
  external:
    url: http://grafana:3000
    apiKey:
      name: grafana-credentials
      key: GRAFANA_TOKEN

A GrafanaDatasource (spec.datasource holds the same fields as data source provisioning) and a GrafanaDashboard follow the same instanceSelector pattern. A dashboard can carry its JSON inline, from a ConfigMap (configMapRef), or from grafana.com (grafanaCom), and folder names the folder (the operator creates it if it does not exist):

apiVersion: grafana.integreatly.org/v1beta1
kind: GrafanaDashboard
metadata:
  name: bookshelf-service-health
spec:
  instanceSelector:
    matchLabels:
      dashboards: bookshelf-grafana
  folder: bookshelf
  resyncPeriod: 30s
  json: >
    {
      "title": "Bookshelf service health",
      "uid": "bookshelf-service-health"
    }

The folder the operator creates gets its own generated uid; if alert rules or permissions refer to the folder by uid bookshelf, create the folder with another tool (or reference it by title). The operator also has a GrafanaFolder resource (with sub-folder support) and resources for alert rule groups, contact points, mute timings and notification policies, listed in its examples.

For GitOps, put these manifests in a Git repository and let Argo CD apply them. The official guide uses an Argo CD Application whose source is the folder with the manifests (with directory.recurse on), whose destination is the in-cluster server https://kubernetes.default.svc, and whose sync policy is automated with prune and selfHeal; a commit that edits the dashboard JSON is then synced to the custom resource and the operator pushes it to Grafana.

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: bookshelf-grafana
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/example/bookshelf-gitops
    targetRevision: HEAD
    path: grafana
    directory:
      recurse: true
  destination:
    server: https://kubernetes.default.svc
    namespace: monitoring
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true

prune makes Argo CD delete custom resources that were removed from Git, and the operator then deletes the dashboards; selfHeal reverts manual changes to the custom resources (not to the dashboard in the Grafana UI). Cluster-level topics such as the monitoring stack of Kubernetes are on Observability, Logging and Metrics.

Source: Grafana docs — Grafana Operator and Grafana Crossplane provider, Manage data sources and dashboards with folders, Manage dashboards with GitOps using Argo CD and the operator’s resource examples (external instances: the spec.external block with url and apiKey or admin credentials). The Argo CD manifest above follows the key settings of the official guide.

What can go wrong

  • Two owners for one dashboard. A file provider, Terraform, the operator and Git Sync each overwrite what another created under the same uid. With Git Sync, an existing unmanaged resource with the same uid blocks the import until it is removed. Give every dashboard exactly one owner, and give each tool its own folder.

  • Edits that vanish. With allowUiUpdates: true, a saved UI change is overwritten the next time the file changes; with Terraform the next apply reverts it. Decide that the UI is for drafting and export the result back to Git.

  • Provider scan misses changes. On a Docker bind mount or a network file system, file events may not arrive at an updateIntervalSeconds of 10 or less. Use a larger value to force polling.

  • Deletions on removal. With disableDeletion: false, removing a provider file removes its dashboards from the database.

  • Interpolation in the wrong place. $VAR and ${VAR} are expanded in provisioning configuration values, not inside dashboard files. Write a literal dollar sign in a provisioning value with care, and test the result in the lab.

  • Wrong schema for the version. On Grafana 13 a V2 or dynamic dashboard needs the Kubernetes resource format; the legacy Terraform resource then needs the full document. Match the resource to the dashboard API version.

  • Git Sync on 13.0.0. Do not upgrade to 13.0.0; use 13.0.1 or later.

  • Git Sync reach. Webhooks need a Grafana that the Git server can call, and a Pure Git repository has no webhooks, so it only polls. An internal Git host is blocked until it is listed in allowed_git_urls.

  • Secrets in Git. Dashboards seldom hold secrets, but repository tokens, service account tokens and data source credentials do. Keep them in Secrets, CI secret stores or environment variables, as described on Observability as Code.

  • Cardinality in generated dashboards. A generator makes it cheap to add a panel per service and per route; the queries still run in the browser every refresh. Review the generated result, not only the code.

Verify in the lab

These checks use the lab on Hands-on Lab with the grafana profile running; GRAFANA_TOKEN is a token of the ci-provisioner service account.

  1. Classic provisioning. Put the dashboard JSON in ./dashboards, the provider file in ./provisioning/dashboards, and restart Grafana. Open Dashboards and confirm "Bookshelf service health" appears in the folder bookshelf. Open it, change a panel and select Save: Grafana must answer "Cannot save provisioned dashboard". Edit the file, wait one updateIntervalSeconds, and confirm the change appears without a restart.

  2. The API read. Run the curl read call above and check that metadata.name is bookshelf-service-health and that spec.panels matches the UI. If the call returns 404, the dashboard has another uid.

  3. Generate and push. Run the TypeScript program, inspect dashboard.json (two panels, uid bookshelf-service-health), push it with gcx resources push dashboards --path ./dashboard.json, and reload the dashboard. Change the unit in the program, push again, and see the unit change.

  4. Git Sync. Connect a scratch repository with the repository YAML above (workflows write and branch), push it with gcx resources push --path ./git-sync, confirm the repository status in Administration > General > Provisioning, edit a panel title in the UI, save it to a new branch, and check that a pull request can be opened. Merge it and confirm the dashboard shows the new title for other users.

  5. Drift. Edit the Terraform- or file-managed dashboard in the UI (if the tool allows it) and run the tool again; the dashboard returns to the definition in Git. This is the behaviour the team has to agree on.

  6. Clean up. Delete the scratch repository with gcx resources delete repository/bookshelf-dashboards; choose whether Grafana keeps or deletes the synced dashboards.

For the complete lab walk-through that connects these dashboards with alert rules and the notification pipeline, see Bookshelf End to End.

In the books

Chapter 13 of Getting Started with Grafana (McCollam, Apress) describes dashboard provisioning as a YAML file that tells Grafana where to find the dashboard JSON files on disk and how often to check them, so dashboards can change without a restart. It also notes that provisioned resources can be changed only through the provisioning system, not in the UI or the API, and that provisioning is not available in Grafana Cloud. The provider format and the read-only behaviour are as shown above, but newer Grafana versions let the provider decide this with allowUiUpdates, and the legacy API the chapter uses for dashboards (/api/dashboards) is now deprecated in favour of /apis. Chapter 10 of Observability with Grafana (Chapman and Holmes, Packt) shows Terraform’s grafana_dashboard with config_json = file(...) and overwrite = true, and suggests iterating over a folder of JSON files with fileset and for_each, and recommends separating the tooling that deploys dashboards from the tooling that manages the observability infrastructure. The resource names and the Grizzly and Grafonnet tooling of that period have since changed: the Foundation SDK and gcx replace them, and Grafana 13 adds resources for the new dashboard APIs.