Observability 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 and Kibana 9.5.x.

Dashboards and alert rules start life as something a person built in a browser, and for a while that works. Then the service gets a second environment, somebody edits a threshold during an incident and forgets to say so, a dashboard is deleted by accident, a colleague asks why a rule was changed, and nobody can answer. Observability as code is the practice of treating those artefacts like any other source: a text definition in Git, changed by pull request, applied by a pipeline, and compared regularly with what is running. This page explains why, compares the options in Grafana and Kibana, and builds a small pipeline for the Bookshelf example.

The ideas are the ones in the Terraform section of this site, and this page reuses them rather than repeating them. Start with Introduction and Infrastructure as Code, State, Sensitive Data, Ephemeral Values and Write-only Arguments, CI/CD and Automation and Code Quality and Security Scanning. The tool-specific pages that go deeper are Dashboards as Code (Grafana), Provisioning Alerting Resources, Dashboards as Code (Kibana) and Alerting APIs and Terraform. The artefacts being managed are designed on Designing Actionable Alerts and Notifications and Incident Response.

Why put observability in Git

Benefit What it looks like in practice

Review

A change to a threshold, a route or a panel is a diff in a pull request. A second person checks that the alert still has an owner and a runbook, and the discussion stays attached to the change.

Environments

The same definitions are applied to development, staging and production with different variables (data source UIDs, webhook URLs, thresholds). Staging is a rehearsal of production, not a hand-built approximation.

Drift detection

A scheduled plan compares the repository with the running system. A threshold edited in the UI at 3 a.m. shows up on the next run, instead of surviving unnoticed for months.

Rollback and history

Reverting a commit and applying restores the earlier alert, route or dashboard. git log answers who changed the rule and why.

Recovery

A deleted folder, a lost Grafana database or a new region is rebuilt by applying the repository. Without it, the alerting configuration may be the only part of the platform that nobody can recreate.

Policy

Required labels and annotations, naming conventions and forbidden settings can be checked in CI before anything is applied.

There is a cost, and it is mostly about people. Once definitions are in code, the UI becomes a place to explore and draft, not to change production, and the team must agree on that. Grafana helps by marking provisioned resources as read-only in the UI (provenance), so the editing path is unambiguous; Kibana does not, and the Elastic documentation warns that changes made directly in the UI are overwritten on the next deployment when Git is the source of truth.

What to manage as code

Not everything has the same shape. A practical split for Bookshelf:

Artefact Grafana Kibana

Dashboards

JSON (classic model, or the Kubernetes-style schema in Grafana 13), generated by hand, exported, or built with the Foundation SDK.

Dashboards API JSON, or the Terraform elasticstack_kibana_dashboard resource (technical preview).

Alert rules

Rule groups (file provisioning, grafana_rule_group, the provisioning API) in folders.

Rules (elasticstack_kibana_alerting_rule, the Alerting API, exported saved objects).

Routing

The notification policy tree: a single resource.

Rule actions and connectors; there is no central tree.

Destinations

Contact points, message templates, mute timings.

Connectors, maintenance windows, case templates.

Data sources and secrets

Data source provisioning with secureJsonData; credentials injected at deploy time.

Connector secrets, API keys, data views with stable IDs.

Runbooks

Linked from the runbook_url annotation; the text lives in the repository’s docs.

The artifacts attribute of the rule can attach the investigation guide and dashboards.

Keep human-readable names and stable identifiers (rule UIDs, dashboard UIDs, data view IDs) in the definitions. Kibana dashboards reference data views and library visualizations by ID, and auto-generated IDs differ between environments, so panels show no data until the references resolve; the Elastic guide recommends Terraform (which maps IDs per environment), or ES|QL panels that carry no external references, or giving the referenced objects the same IDs in every environment.

The options compared

Option Covers Strengths Limits

Grafana file provisioning (classic)

Dashboards (providers pointing to a folder of JSON), data sources, alerting resources (provisioning/alerting)

No extra tooling, loaded at startup, supports $ENV interpolation. Provisioned alerting resources are read-only in the UI.

Needs files on the Grafana host. Not available in Grafana Cloud. Importing an existing alerting resource results in a conflict.

Grafana on-prem file provisioning (Grafana 12 and later, OSS and Enterprise)

Dashboards and folders, through a Repository resource of type local; up to 10 repositories

Provisioned items appear under a provisioned folder and are edited only in the files.

Dashboards only for now, does not replace classic provisioning, not available in Grafana Cloud.

Grafana HTTP APIs

Everything, including the alerting provisioning API and the /apis Kubernetes-style API

Scriptable from any language, export endpoints return provisioning-ready YAML or JSON.

You write the diffing and ordering. /api is deprecated in favour of /apis since 13.0, and numeric data source IDs are disabled by default.

Terraform provider grafana/grafana

The broadest set: dashboards, data sources, alerting, plugins, collectors, synthetic monitoring, IRM, identity and access

Plan before apply, state, drift detection, works for OSS, Enterprise and Cloud.

State holds secrets. Dashboard JSON inside HCL is verbose. A provider major version can change arguments.

Grafana Git Sync (generally available in Grafana 13.0)

Dashboards (JSON) in a Git repository, synced both ways

Edit in the UI or in Git, commit and pull-request workflow, polling every 60 seconds or immediate with webhooks.

Dashboards only; the documentation lists no alert rules. Do not use 13.0.0 itself (a migration bug); use 13.0.1 or later.

Foundation SDK

Dashboards and resources defined as typed code in Go, TypeScript, Python, PHP or Java

Compile-time checks, reuse through functions and libraries.

Generates JSON; you still deploy it (API, CLI or Git Sync).

Grafana Operator

Dashboards, folders, alerts and data sources as Kubernetes custom resources

Fits GitOps with Argo CD or Flux in a cluster.

A community project, not commercially supported by Grafana.

gcx (Grafana CLI)

Works with Cloud, Enterprise and OSS, built on the versioned APIs

The current official CLI, also meant for AI agents.

grafanactl is deprecated, Grizzly was removed and Grafonnet is not officially supported.

Kibana Dashboards API

Dashboards (and PUT /api/visualizations/{id} for library visualizations)

Diffable JSON, upsert with a chosen ID.

The documentation points to the API reference for schemas; the Terraform dashboard resource is in technical preview.

Kibana saved objects (export and import)

Dashboards, data views, rules (exported rules are disabled and must be enabled after import)

Built in, works across spaces and clusters.

NDJSON is hard to review; references are by ID.

Terraform provider elastic/elasticstack

Rules, connectors, maintenance windows, data views, case templates, SLOs, spaces, and more

Plan, state and drift detection, per-space deployment.

Some resources are in preview; some attributes need a minimum stack version.

Source: Grafana docs — As code and provisioning and Elastic docs — Manage dashboards as code. The Grafana 13 changes (/apis, numeric IDs, Git Sync and dynamic dashboards generally available) are from What’s new in Grafana 13; the Terraform resource lists are from the provider documentation linked below.

A decision rule that works for most teams: use Terraform for alert rules, contact points, policies, connectors and folders, because plans and state matter most there; use Git Sync or the Foundation SDK with a pipeline for Grafana dashboards if the people editing them prefer a UI loop; use the Dashboards API with a pipeline or Terraform for Kibana dashboards; and do not mix two tools over the same resource, because the second one will overwrite or fight the first.

Grafana: file provisioning

File provisioning is the oldest mechanism and needs no tooling beyond the container image. A provider file tells Grafana where to find dashboard JSON, and Grafana rescans the folder on an interval.

# provisioning/dashboards/bookshelf.yaml
apiVersion: 1

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

Reference: Grafana docs — Provision Grafana. To use foldersFromFilesStructure, leave the folder and folderUid options unset. With allowUiUpdates: false the provisioned dashboards cannot be saved from the UI, which is what you want when the files are the source of truth.

Alerting resources (rules, contact points, notification policies, mute timings and template groups) are loaded from provisioning/alerting, at startup and again on request through the Grafana Admin API. Provisioned alerting resources cannot be edited in the UI, and importing a resource that already exists results in a conflict, so provision into an empty state or delete first. The notification policy tree is a single resource, so provisioning it overwrites all existing policies, and resetPolicies restores the default tree. The YAML for each resource type is on Provisioning Alerting Resources, and the first example of a rule file is on Designing Actionable Alerts.

You do not have to write these files by hand. The Grafana UI exports alert rules (all rules, a folder, or a group), contact points, the notification policy tree and mute timings as YAML, JSON or Terraform (HCL), and the Modify export feature exports a rule you have edited without saving it. A new rule definition can be exported only as HCL. Notification template groups have no export; copy their name and content manually. The alerting HTTP API has matching /export endpoints that return YAML or JSON ready for provisioning (the normal endpoints return JSON that is not valid for file provisioning). The export of a working rule is the dependable way to author the model blobs that depend on the data source.

Grafana: Terraform

Terraform adds two things file provisioning lacks: a plan that shows exactly what will change, and state that remembers what Terraform created, so removing a resource from the code removes it from Grafana. The provider is grafana/grafana (version 4.54.0 was the latest release on 2026-11-08); it works against Grafana OSS, Enterprise and Cloud.

Create a service account in Grafana, give it a role that grants access to the alerting provisioning API (the documentation points to the fixed:alerting.provisioning.* roles) and the permissions for the other resources you manage, and create a token for it. API keys have been replaced by service accounts, so do not use the legacy keys. The provider reads the Grafana URL from GRAFANA_URL and the credentials from GRAFANA_AUTH (a token, or username:password), so neither needs to appear in the files.

The following configuration manages the Bookshelf folder, the 5xx rule, a contact point and the routing, in one place. The model of the query stage is data-source specific; generate the real value by exporting a rule from the UI as HCL.

terraform {
  required_providers {
    grafana = {
      source  = "grafana/grafana"
      version = ">= 4.47.0"
    }
  }
}

# Credentials come from GRAFANA_URL and GRAFANA_AUTH in the environment.
provider "grafana" {}

variable "prometheus_uid" {
  type        = string
  description = "UID of the Prometheus-compatible data source."
}

variable "webhook_url" {
  type        = string
  description = "URL of the notification receiver."
  sensitive   = true
}

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

resource "grafana_contact_point" "webhook" {
  name = "bookshelf-webhook"

  webhook {
    url = var.webhook_url
  }
}

resource "grafana_rule_group" "service_level" {
  name             = "bookshelf-service-level"
  folder_uid       = grafana_folder.bookshelf.uid
  interval_seconds = 60

  rule {
    name            = "Bookshelf high 5xx ratio"
    condition       = "C"
    for             = "5m"
    keep_firing_for = "5m"
    no_data_state   = "NoData"
    exec_err_state  = "Error"

    labels = {
      team        = "bookshelf-sre"
      application = "bookshelf"
      severity = "critical"
    }
    annotations = {
      summary     = "More than 5% of Bookshelf requests are failing with 5xx."
      runbook_url = "https://wiki.example.com/runbooks/bookshelf-5xx"
    }

    data {
      ref_id         = "A"
      datasource_uid = var.prometheus_uid
      relative_time_range {
        from = 600
        to   = 0
      }
      model = jsonencode({
        refId   = "A"
        instant = true
        expr    = "sum(rate(http_server_requests_seconds_count{application=\"bookshelf\",status=~\"5..\"}[5m])) / sum(rate(http_server_requests_seconds_count{application=\"bookshelf\"}[5m]))"
      })
    }

    data {
      ref_id         = "B"
      datasource_uid = "__expr__"
      relative_time_range {
        from = 0
        to   = 0
      }
      model = jsonencode({
        refId      = "B"
        type       = "reduce"
        expression = "A"
        reducer    = "last"
      })
    }

    data {
      ref_id         = "C"
      datasource_uid = "__expr__"
      relative_time_range {
        from = 0
        to   = 0
      }
      model = jsonencode({
        refId      = "C"
        type       = "math"
        expression = "$B > 0.05"
      })
    }
  }
}

resource "grafana_notification_policy" "tree" {
  group_by      = ["alertname", "grafana_folder", "service"]
  contact_point = grafana_contact_point.webhook.name

  policy {
    contact_point = grafana_contact_point.webhook.name

    matcher {
      label = "severity"
      match = "="
      value = "critical"
    }
  }
}

Reference: Grafana docs — Provision alerting resources with Terraform, grafana_rule_group, grafana_notification_policy and grafana_contact_point. The data block shapes and the expression models follow the documented examples; the $B > 0.05 Math expression uses the same syntax as the documented $B > 70. The data source UID of the lab is a variable on purpose.

Four behaviours cause most surprises:

  • Provenance. Resources created by Terraform are read-only in the Grafana UI. Setting disable_provenance = true on a resource allows UI edits, which is a deliberate exception and should be rare, because it re-opens the door to drift.

  • The policy tree is one resource. grafana_notification_policy manages the entire tree and overwrites its policies; it does not overwrite the internal policies Grafana creates when a rule selects a contact point directly. Only one Terraform configuration per Grafana organisation may own it.

  • Rule options map to Terraform values. no_data_state accepts OK, NoData, KeepLast and Alerting, and exec_err_state accepts OK, Error, KeepLast and Alerting. keep_firing_for and missing_series_evals_to_resolve exist too. Missing-data semantics are explained on Designing Actionable Alerts.

  • Dashboards in Grafana 13. grafana_dashboard takes the complete JSON model as config_json and an optional folder. The provider’s own documentation says to use the resource that corresponds to your dashboard’s API version for Kubernetes-style dashboards (the provider now ships grafana_apps_dashboard_dashboard_v1beta1, v2beta1 and v2 resources next to the legacy one); if you use the legacy resource with a Kubernetes-style definition on Grafana 13 you must supply the full document with apiVersion, kind, metadata and spec.

resource "grafana_dashboard" "service_health" {
  folder      = grafana_folder.bookshelf.uid
  config_json = file("${path.module}/dashboards/bookshelf-service-health.json")
  overwrite   = true
}

Reference: grafana_dashboard and Grafana docs — Terraform. The dashboard file is the JSON model of the lab’s "Bookshelf service health" dashboard (export it from the dashboard’s JSON model view).

Source: Grafana docs — Manage Grafana with Terraform. The provider also manages IRM on Grafana Cloud (integrations, escalation policies and on-call schedules), plugins, saved queries and Fleet Management, according to the same page.

Grafana: Git Sync, Foundation SDK, Operator and gcx

Git Sync stores dashboards as JSON in a Git repository and keeps the repository and a Grafana instance in step in both directions: edit in the Grafana UI and commit from there, or edit in Git and let Grafana pull. It works with any Git provider through the "Pure Git" repository type and has enhanced integrations for GitHub, GitHub Enterprise, GitLab and Bitbucket. Without webhooks Grafana polls the repository every 60 seconds by default (configurable); with webhooks, changes arrive almost immediately. It can require pull-request approval before changes reach the main branch, which gives dashboards the same review as code. Git Sync became generally available in Grafana 13.0 (along with dynamic dashboards, which migrate existing dashboards to the new schema when opened, one way); the documentation describes deployment scenarios from a single instance to development and production pairs and multi-region setups. The provider has a repository resource for it, at an alpha API version, so check its maturity before building on it.

The Foundation SDK defines dashboards and other resources as strongly typed code in Go, TypeScript, Python, PHP or Java, with compile-time checks and Git history. A minimal TypeScript program that prints a dashboard as JSON:

import * as dashboard from '@grafana/grafana-foundation-sdk/dashboard';
import * as timeseries from '@grafana/grafana-foundation-sdk/timeseries';
import * as testdata from '@grafana/grafana-foundation-sdk/testdata';

const ds = { type: 'grafana-testdata-datasource', uid: 'testdata' };

const builder = new dashboard.DashboardBuilder('My Dashboard').withPanel(
  new timeseries.PanelBuilder()
    .title('Random Time Series')
    .datasource(ds)
    .withTarget(new testdata.DataqueryBuilder().scenarioId('random_walk'))
);

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

Source: Grafana docs — Foundation SDK (install with npm install @grafana/grafana-foundation-sdk). The page lists Grafana 10.0 or later as the requirement and describes deploying the generated JSON through the import feature, the Grafana API, the Grafana CLI or Git Sync. It replaces Grafonnet, which is not officially supported, and Grizzly, which was removed.

The Grafana Operator manages Grafana instances and resources from Kubernetes custom resources, mainly dashboards, folders, alerts and data sources, and fits clusters that already use GitOps (see Observability, Logging and Metrics). The documentation states that it is a community project and not commercially supported by Grafana; its resource list and examples live in the operator’s own documentation at grafana.github.io/grafana-operator.

gcx is Grafana’s CLI for Cloud, Enterprise and OSS, built on the versioned APIs, and the documentation recommends it for working with AI agents; it supersedes the deprecated grafanactl. The page does not state its release maturity, and this page does not reproduce command syntax, so use the gcx documentation and its repository at https://github.com/grafana/gcx for the current commands. The standard Grafana commands themselves changed in 13.0: grafana-cli and grafana-server are now grafana cli and grafana server.

Kibana: Dashboards API, saved objects and Terraform

The Elastic Stack offers the same split. The Dashboards API exports a dashboard as API-compatible JSON from the share menu (the export removes the internal state that makes raw saved objects hard to read), you commit the file, review the structured diff, and deploy it to each environment. PUT /api/dashboards/{id} creates or replaces a dashboard with a chosen ID, so re-importing the exported definition recreates the same object; POST generates a new ID every time, which is why the documentation recommends PUT for dashboards and for library visualizations (PUT /api/visualizations/{id}). To deploy into a space, include the space ID in the request URL; the export flow can open a pre-populated request in Kibana Dev Tools Console, where you set the destination space before sending.

# Deploy a dashboard definition under a stable ID (adapt the URL and credentials to your environment).
curl -sS -X PUT "$KIBANA_URL/api/dashboards/bookshelf-service-health" \
  -H "kbn-xsrf: true" \
  -H "Content-Type: application/json" \
  -H "Authorization: ApiKey $KIBANA_API_KEY" \
  --data-binary @dashboards/bookshelf-service-health.json

Reference: Elastic docs — Manage dashboards as code. The page names the PUT endpoint and refers to the Dashboards API specification for the request schema and authentication, so build the body from an export rather than from memory. The workflow is generally available on Elastic Stack 9.5 and in preview in 9.4, and generally available on Serverless; data views have their own API (generally available from 9.0 to 9.5), and a v2 data views API sets custom IDs on Serverless and is listed as planned for the Elastic Stack.

Saved objects (export and import through Stack Management) remain the built-in way to move dashboards, data views and rules between clusters or spaces; exported rules are disabled and you are prompted to enable them after import, and stack monitoring rules are created automatically and cannot be managed this way. The files are NDJSON with references by ID, so reviewing them is harder than reviewing the Dashboards API JSON.

The Terraform provider elastic/elasticstack (the examples use version = "~> 0.16") manages rules, connectors, maintenance windows and more. The documentation notes that rules can be managed as code with the elasticstack_kibana_alerting_rule resource, and the dashboards guide says the elasticstack_kibana_dashboard resource is in technical preview and does not yet expose every panel type, with no automatic conversion from an export: you can adopt an existing dashboard with terraform import, but you write the matching configuration by hand.

terraform {
  required_providers {
    elasticstack = {
      source  = "elastic/elasticstack"
      version = "~> 0.16"
    }
  }
}

# Credentials come from KIBANA_ENDPOINT and KIBANA_API_KEY (or KIBANA_USERNAME and KIBANA_PASSWORD).
provider "elasticstack" {
  kibana {}
}

resource "elasticstack_kibana_alerting_rule" "bookshelf_errors" {
  name         = "bookshelf-error-logs"
  consumer     = "alerts"
  rule_type_id = ".index-threshold"
  interval     = "1m"
  enabled      = true
  tags         = ["bookshelf", "bookshelf-sre"]

  params = jsonencode({
    aggType             = "count"
    groupBy             = "all"
    timeWindowSize      = 5
    timeWindowUnit      = "m"
    threshold           = [20]
    thresholdComparator = ">"
    index               = ["bookshelf-logs-*"]
    timeField           = "@timestamp"
  })

  alert_delay = 3

  flapping = {
    look_back_window        = 10
    status_change_threshold = 6
  }

  artifacts = {
    investigation_guide = {
      content = "1. Check the Bookshelf service health dashboard.\n2. Look for a failing dependency in the error logs.\n3. Roll back the last deployment if the errors started with it."
    }
    dashboards = [
      { id = "bookshelf-service-health" }
    ]
  }
}

Reference: elasticstack_kibana_alerting_rule and provider configuration. Points from that page: alert_delay is the number of consecutive runs that must meet the conditions before an alert occurs; the rule-level flapping object (Kibana 8.16 or later) requires both look_back_window and status_change_threshold; artifacts needs Elastic Stack 9.1 or later to write, and before 9.5.0 the Kibana API does not return artifacts, so terraform import will not populate them and drift made outside Terraform will not be detected; notify_when and throttle at the rule level are deprecated since 8.13 in favour of the per-action frequency block; rule_id can be any string on Kibana 8.17 and later; space_id selects the space. The rule here deliberately has no actions; the connector and action example is on Notifications and Incident Response. The index name is a lab assumption.

Authentication for the Kibana provider block comes from static username, password and endpoints or an api_key, or from the environment variables KIBANA_ENDPOINT, KIBANA_USERNAME, KIBANA_PASSWORD, KIBANA_API_KEY and KIBANA_BEARER_TOKEN; if no Kibana credentials are given, the provider falls back to those in the elasticsearch block. An API key for rules has a documented limit: key-based authentication for alerting rule resources needs Elastic Stack 8.8.0 or later.

Secrets

Observability definitions are full of secrets: webhook URLs that embed tokens, PagerDuty routing keys, Slack tokens, data source passwords and the API tokens the pipeline itself uses. The rules are the same as for any infrastructure code, with a few tool-specific details.

  • Never commit a secret. Keep values in the CI secret store or a secrets manager, and run a secret scanner on every pull request (see Code Quality and Security Scanning).

  • Grafana file provisioning interpolates $VARIABLE and ${VARIABLE} in provisioning configuration (not in dashboard definition files). An unset variable becomes an empty string, a literal dollar sign is written $$, and interpolation does not apply to alert rule annotations, the query model, template contents or mute timing definitions, which is why a template containing {{ $labels }} does not break. Data source passwords belong in secureJsonData.

  • Terraform state contains secrets. Mark variables sensitive = true, store state in a remote backend with encryption and tight access (see Backends and Remote State), and treat saved plan files as secrets (see CI/CD and Automation). The Kibana connector resource goes a step further: secrets_wo accepts the same JSON as secrets but is never persisted to state (write-only arguments need Terraform 1.11 or later), and secrets_wo_version is bumped to trigger a re-send when the secret rotates. See Sensitive Data, Ephemeral Values and Write-only Arguments.

  • Least privilege for the pipeline. Give the Grafana service account or the Kibana API key only the roles and privileges for the resources it manages, and use a read-only identity for pull-request plans when your tools allow it. Grafana additionally protects the sensitive fields of contact points: users with edit permission cannot change protected fields of existing integrations unless they hold the alert.notifications.receivers.protected:write action.

  • Inspect every export. Neither the Grafana export page nor the Elastic dashboard guide describes how secrets are handled in exports, so read each exported file for tokens before committing it.

A plan-then-apply pipeline

The pipeline is the Terraform pipeline already described in CI/CD and Automation, applied to the Grafana configuration: format and validate and scan on every push, a plan on every pull request that reviewers can read, an apply only from the main branch, and a scheduled plan that reports drift. The workflow below keeps the observability code in observability/ and uses repository secrets for the Grafana token. Pin the actions to the majors that page lists (actions/checkout v7, hashicorp/setup-terraform v4) and let Dependabot update them.

# .github/workflows/observability.yml
name: observability

on:
  pull_request:
    paths: ["observability/**"]
  push:
    branches: [main]
    paths: ["observability/**"]
  schedule:
    - cron: "17 6 * * *"

permissions:
  contents: read

env:
  TF_IN_AUTOMATION: "true"
  TF_INPUT: "false"
  GRAFANA_URL: ${{ vars.GRAFANA_URL }}
  GRAFANA_AUTH: ${{ secrets.GRAFANA_AUTH }}
  TF_VAR_prometheus_uid: ${{ vars.PROMETHEUS_UID }}
  TF_VAR_webhook_url: ${{ secrets.WEBHOOK_URL }}

defaults:
  run:
    working-directory: observability

jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_wrapper: false
      - run: terraform fmt -check -recursive
      - run: terraform init
      - run: terraform validate
      - run: terraform plan -no-color -lock-timeout=5m

  apply:
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    environment: observability-production
    steps:
      - uses: actions/checkout@v7
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_wrapper: false
      - run: terraform init
      - run: terraform plan -no-color -lock-timeout=5m -out=tfplan
      - run: terraform apply -no-color -lock-timeout=5m tfplan

  drift:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: hashicorp/setup-terraform@v4
        with:
          terraform_wrapper: false
      - run: terraform init
      - name: Detect drift
        run: |
          set +e
          terraform plan -no-color -detailed-exitcode -lock-timeout=5m
          code=$?
          if [ "$code" -eq 2 ]; then echo "::warning::Observability configuration has drifted"; fi
          [ "$code" -ne 1 ]

Reference: the structure follows HashiCorp Developer — Automate Terraform and the site’s own pipeline, and -detailed-exitcode is documented at terraform plan (0 means no changes, 1 error, 2 changes present). A real setup adds a remote backend with locking (the snippet assumes a backend block in observability/), the environment protection rule with required reviewers that gates the apply, and the scanners from the Terraform section. For Kibana, replace the variables with KIBANA_ENDPOINT and KIBANA_API_KEY; for dashboards deployed through the Dashboards API, add a job that sends each file with the curl call above after the Terraform apply.

Two additions make this pipeline fit observability specifically. First, add a policy check that fails the pull request when a rule lacks team, severity, summary or runbook_url; Grafana’s Alert Advisor can enforce the same contract at provisioning time for Terraform and the provisioning API (see Designing Actionable Alerts), and a CI check catches it earlier. Second, keep the drift job’s output visible: a drift warning that nobody reads is the same failure as an alert nobody reads.

Drift, ownership and rollback

Drift is any difference between the repository and the running system. The usual causes are an emergency edit in the UI (possible for Kibana and, for Grafana, only when provenance is disabled or the resource is not provisioned), an older manual resource that Terraform never imported, and a tool that was not told to stop. The remedies are to make the editing path unambiguous (provisioned resources are read-only in Grafana), to run the scheduled plan, and to follow a simple rule: an emergency change is allowed, but the next step is a pull request that makes the repository match, reviewed after the incident as described on Notifications and Incident Response.

Rollback is git revert followed by the same pipeline. For Terraform state, make sure nothing else changed in the meantime; for Git Sync, revert the commit in the repository and let Grafana pull. Grafana also keeps a dashboard’s version history, and the message argument of grafana_dashboard writes a commit message into it.

In the books

Chapter 10 of Observability with Grafana (Chapman and Holmes, Packt, 2023) argues for automating Grafana, covering Helm and Ansible for collection infrastructure, the Grafana Cloud API, and Terraform or Ansible for dashboards and alerts. The case it makes has not changed. The details have: the Grafana Agent installation it automates has reached end of life and Grafana Alloy replaces it, the dashboards-as-code tools it points to (Grizzly and Grafonnet) are gone or unsupported and the Foundation SDK and gcx took their place, and Terraform resource names and the provider version have moved on, so run terraform init -upgrade against the current registry documentation rather than copying its code. Chapter 13 of Getting Started with Grafana (McCollam, Apress, 2022) covers the REST API for dashboards, folders and data sources and file provisioning; its API keys are replaced by service accounts, /api is deprecated in favour of /apis since Grafana 13.0, and its Grafana 8.x examples predate Git Sync and the Kubernetes-style dashboard schema. Publisher pages: Observability with Grafana (Packt) and Getting Started with Grafana (Apress).

Verify in the lab

  • The lab already file-provisions the bookshelf-webhook contact point, the bookshelf-service-level rule group and the policy tree, so first move grafana/provisioning/alerting/bookshelf.yaml out of the lab directory and recreate Grafana with docker compose --profile grafana down -v and docker compose --profile grafana up -d. Then apply the Terraform from this page against the lab Grafana and run terraform plan again: it must report no changes. A plan that keeps proposing a change to a rule usually means a model field Grafana normalises; export the rule as HCL and compare.

  • Open the rule in the Grafana UI: it should be marked as provisioned and be read-only. Then set disable_provenance = true, apply, edit the threshold in the UI, and run the plan to watch the drift appear, then remove the flag and apply to restore the declared value.

  • Export the same rule from the UI as YAML and as HCL and diff both against your code. Export a contact point and look for secrets before committing it.

  • For Kibana, create the rule with Terraform, edit its check interval in Stack Management, run the plan, and confirm the drift is reported. Then deploy a dashboard with the PUT call twice and confirm that the second call replaces the first instead of creating a duplicate.

  • Run the workflow on a branch: the plan job must show the change in the pull request, and the apply job must wait for the environment’s reviewer.