Comprehensive guide to observability as code for production observability and monitoring systems.
This page is about treating every facet of your observability stack—metrics, logs, traces, alerts, and dashboards—as code that lives in version control, gets reviewed, and undergoes the same CI/CD pipelines as application code. It matters when your observability configuration drifts from your deployment state, when on-call engineers cannot trace how an alert was generated, or when a dashboard disappears after a platform upgrade. The core promise is that observability configuration should be discoverable, reviewable, reproducible, and resistant to the silent rot that comes from manual UI changes.
Traditional observability workflows create configuration through point-and-click UIs or imperative scripts that are easy to lose track of. A developer adjusts a alert threshold in the web UI; another developer rotates the cluster and the threshold is forgotten; a platform upgrade renames an API field and the dashboard goes silent. Each of these events is a failure of governance, not of instrumentation. Writing observability as code shifts the source of truth from a web browser to a repository, where every change is tracked, every reviewer can validate the intent, and every apply is an explicit, auditable event.
The pattern applies regardless of which observability platform you run. The mechanics are always the same: a declarative or semi-declarative definition of what should be observed, a pipeline that transforms that definition into the platform’s native format, and a runtime that enforces the desired state. What follows is a concrete, tool-agnostic workflow that works with Kubernetes, Prometheus, Loki, Jaeger, or any system that exposes an API or accepts configuration files.
The first step is to decide what aspects of observability you codify. Most teams start with alerts, then expand to dashboards, then to instrumentations definitions. The key is that the definition lives in a format your version control system can diff and merge—YAML, JSON, or a domain-specific language that compiles to the platform’s expected format.
Alert rules are the most common entry point. A typical Prometheus rule looks like this:
groups:
- name: example-rules
rules:
- alert: HighRequestLatency
expr: histogram_quantile(0.95, sum(rate(request_duration_seconds_bucket[5m])) by (le)) > 0.5
for: 5m
labels:
severity: critical
annotations:
summary: "95th percentile request latency > 500ms"
description: "User-facing requests have been slow for the last 5 minutes."
Store this in alerts/ under your repository root. The file format is plain YAML, so git diff shows exactly which threshold or label changed between commits. When you merge a change, you are explicitly deciding that the new rule should replace the old one.
Dashboards are typically JSON or a vendor-specific format, but many platforms accept a standardized shape. For Grafana, a dashboard JSON file might contain:
{
"dashboard": {
"id": null,
"uid": "example-dashboard",
"title": "Service Health",
"timezone": "browser",
"panels": [
{
"type": "stat",
"title": "Error Rate",
"datasource": "Prometheus",
"targets": [
{
"expr": "sum(rate(http_requests_total{status=~\"5..\"}[5m])) by (instance)",
"legendFormat": "errors"
}
],
"gridPos": { "x": 0, "y": 0, "w": 12, "h": 4 }
}
],
"schemaVersion": 38,
"version": 1
},
"folderId": 0,
"overwrite": true
}
Save this as dashboards/service-health.json. The overwrite: true flag tells Grafana to replace any existing dashboard with the same UID, ensuring that a git pull followed by an api call renders the intended state.
Some teams go further and codify the instrumentation itself—adding libraries, annotating code, or generating OpenTelemetry collector pipelines. If you use OpenTelemetry, you might have a otel-collector-config.yaml:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
processors:
batch:
timeout: 10s
exporters:
logging:
loglevel: debug
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [logging]
This file becomes the single source of truth for how traces enter your system. When a developer adds a new service, they update this file, not a UI toggle.
Once the definitions are files on disk, the rest of the software development lifecycle applies. Pull requests become the gate for observability changes. A reviewer can see that an alert’s for: duration changed from 1m to 5m, or that a dashboard panel was removed entirely. No more “I thought the threshold was 80% but it’s actually 90%” conversations.
Use git log --oneline --all -- alerts/ to trace when an alert rule was last modified, by whom, and what the previous value was. Pair this with git blame alerts/example-rules.yaml to see the line-by-line history. If your organization requires approvals, configure branch protection rules so that the main branch cannot receive a merge without at least one reviewer approving the observability diff.
For teams that use GitHub Actions, GitLab CI, or similar, add a job that lints the YAML or JSON before it’s applied:
name: lint-observability
on:
pull_request:
paths:
- 'alerts/**'
- 'dashboards/**'
- 'otel-collector-config.yaml'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install yamllint
run: pip install yamllint
- name: Lint alerts
run: yamllint -c .github/yamllint.yaml alerts/
This catches syntax errors, duplicate keys, and indentation problems before the configuration ever reaches the cluster.
The deployment step transforms the repository state into the platform’s native configuration and applies it. The exact command depends on your platform, but the pattern is always the same: read the files, render them into the platform’s format, and issue an upsert or create operation.
If you run Prometheus Operator, the deployment is often a simple kubectl apply:
kubectl apply -f manifests/
The manifests/ directory might contain Alertmanagers, PrometheusRules, PodMonitors, and ServiceMonitors. Each kubectl apply is an idempotent operation—if the resource already exists with the same spec, nothing changes; if the spec differs, the API server patches the resource to match. This idempotency is what makes the “code as desired state” pattern reliable.
For Grafana, you might use curl to push a dashboard:
curl -X POST "http://grafana:3000/api/dashboards/db" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GRAFANA_API_KEY" \
-d @dashboards/service-health.json
The overwrite field inside the JSON (as shown earlier) ensures that the API replaces any existing dashboard with the same UID. If you omit that field or set it to false, the API may create a new dashboard with a suffixed UID, leaving the old one orphaned.
Deploying a collector configuration often involves Helm or a direct file copy into a ConfigMap:
helm upgrade --install otel-collector oci://ghcr.io/open-telemetry/opentelemetry-helm-charts/opentelemetry-collector \
-f otel-collector-values.yaml
The values.yaml file is where you set receivers, processors, and exporters. Because Helm treats the values file as the source of truth, helm diff (from the helm-unittest or helm-diff plugins) can show you exactly what will change before you run the upgrade.
When something goes wrong, the first place to look is the file that should have been applied. The error messages from the platform are usually terse, but the diff between what you wrote and what the platform accepted is the real clue.
Prometheus Rule files require a apiVersion: monitoring.coreos.com/v1 header (or the equivalent for your version of the operator). If you omit it, the API server returns:
error: error parsing YAML: yaml: line 1: mapping values are not allowed in this context
The fix is to ensure every manifest starts with the correct apiVersion and kind. A Makefile target that validates all YAML files against the installed CRD schemas can prevent this class of error:
validate:
kubectl apply --dry-run=client -f manifests/
If your alert rule references a secret for an API token, and the secret name changes, the rule may stop firing without an obvious error. The Prometheus server logs something like:
level=error msg="failed to load rule file" err="secret \"my-api-token\" not found"
The resolution is to ensure the secret exists in the same namespace before applying the rule, or to use a tool like kubectl get secret in your CI pipeline to verify existence.
When two teams define dashboards with the same UID but different folders, the Grafana API may return:
HTTP 409: dashboard already exists with different folder
The overwrite: true flag in the JSON payload tells Grafana to move the dashboard to the specified folder, but if the folder ID in the payload differs from the existing dashboard’s folder, the API may reject the operation. Always include the folderId field when you intend to reorganize dashboards.
The most insidious failure is silent drift. You write an alert rule in YAML, kubectl apply it, and later a team member creates an identical rule through the UI. Now you have two rules, the second of which was never in version control. The Prometheus server evaluates both, potentially firing the alert twice or with different severity labels. The cure is to enforce a policy that all observability configuration must come from the repository; UI access should be restricted or audited.
Platforms evolve their API schemas. A dashboard JSON that validated against Grafana 9.x may fail on Grafana 10.x if a field was renamed or made required. When you upgrade your observability platform, run the linting step against the new version’s schema, or pin your configuration files to the version that generated them.
Configuration files often contain references to secrets, either by name or by inline base64. If you rotate a secret’s value without updating the consumer’s configuration, the system silently falls back to default credentials or fails entirely. Treat secret references as you would any other dependency: bump the version, run integration tests, and document the rotation procedure.
When using Helm, two values.yaml files may define the same key with different defaults. helm install uses the last --set or --values flag, which can override an intended value from a base file. Always run helm template before helm install or helm upgrade to preview the rendered manifest, and use helm diff to confirm the changes are what you expect.
Before merging an observability change, run through this checklist:
yamllint, jsonlint, or kubectl --dry-run).apiVersion/kind matches the installed CRDs.overwrite or replace flag is set appropriately for the resource type.git commit message references the observability component affected (e.g., alerts: adjust latency threshold for checkout service).Treat each of these as a non-negotiable gate. Skipping any one of them is an invitation for the next production incident.
Observability-as-code accumulates technical debt just like application code. If you find yourself writing the same alert rule with only a service name changed, abstract the common parts into a template or a values.yaml parameter. If a dashboard panel’s query becomes so complex that it’s hard to read, extract the query into a Prometheus recording rule or a Grafana variable. The goal is always to reduce duplication and make the configuration easier to reason about.
The day you spend refactoring observability configuration is a day you prevent a future outage. The investment pays off in faster on-call handoffs, clearer audit trails, and a stack that evolves with your organization rather than against it.
This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy