Grafana Dashboards & Observability
Build beautiful, actionable visualizations. Master variables, transformations, provisioning, Loki for logs, and Tempo for distributed tracing correlation.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Provisioning & Advanced Observability · Securing Grafana: Anonymous Access, Admin Secret and Viewer Role
- Why it matters
- A required lesson for SRE, Observability Engineer. Recommended for DevOps Engineer, FinOps / Cloud Optimization, MLOps / LLMOps Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 5 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 09.1
Grafana is a visualization layer. It queries many backends (Prometheus, Loki, Tempo, CloudWatch). Dashboards can be fully provisioned from YAML/JSON for GitOps.
Core Components 09.2
| Feature | Purpose | Example |
|---|---|---|
| Panels | Visualizations | Time series, Stat, Gauge, Table |
| Variables | Dynamic queries | $__interval, $datasource |
| Transformations | Post-processing | Reduce, Join, Organize fields |
| Provisioning | GitOps dashboards | dashboards.yaml + git |
| Loki + Tempo | Logs + Traces | LogQL, TraceQL correlation |
WSL Hands-On Lab 09.3
Deploy Grafana + Loki + Promtail + Import Famous Dashboards
$ docker compose up -d $ # Import dashboard ID 1860 (Node Exporter Full) $ # Add Loki datasource and configure Promtail
- Deploy Grafana + Loki + Prometheus stack with Docker Compose
- Import Node Exporter dashboard 1860
- Build a custom dashboard using variables and transformations
- Configure Promtail to ship logs from containers to Loki
- Explore Grafana Play environment and complete official tutorials
Real-World Project 09.4
Single server infrastructure dashboard
Application RED metrics (Rate, Errors, Duration) dashboard
Multi-tenant orgs + GitOps dashboard provisioning + trace to logs correlation
GitOps Alerting: File-Provisioned Rules, Contact Points & Secret Interpolation
Declarative alert management architecture. Assumptions: Grafana unified alerting >= 10.0 / 11.x, file provisioning directory /etc/grafana/provisioning/alerting/. See official Grafana Alerting File Provisioning and Alerting Provisioning Examples. No credentials, paid external APIs, or live webhook dispatch required.
In production GitOps workflows, alerting rules and notification routing must be managed declaratively alongside dashboards. Grafana provisions alert rules, contact points, and notification policies from apiVersion: 1 YAML files. File-provisioned resources carry a provenance: file metadata lock in the Grafana UI, preventing manual tampering and ensuring version control remains the single source of truth.
apiVersion: 1
groups:
- orgId: 1
name: checkout-slo-alerts
folder: Production-Services
interval: 1m
rules:
- uid: checkout_p99_latency_slo
title: Checkout P99 Latency SLO Breach
condition: C
data:
- refId: A
relativeTimeRange:
from: 600
to: 0
datasourceUid: prometheus-prod
model:
editorMode: code
expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{service="checkout"}[5m])) by (le))
instant: true
range: false
refId: A
- refId: B
relativeTimeRange:
from: 600
to: 0
datasourceUid: __expr__
model:
type: reduce
reducer: last
expression: A
refId: B
- refId: C
relativeTimeRange:
from: 600
to: 0
datasourceUid: __expr__
model:
type: threshold
expression: B
conditions:
- evaluator:
params: [0.5]
type: gt
refId: C
noDataState: NoData
execErrState: Alerting
for: 5m
annotations:
summary: "Checkout P99 latency exceeded 500ms"
description: "Current P99 is {{ $values.B.Value }}s on cluster prod-01"
runbook_url: "https://wiki.internal.net/runbooks/checkout-latency"
labels:
severity: critical
team: checkout-coreThe alert structure evaluates PromQL query A against Prometheus, reduces time-series samples to scalar value B with reducer: last, and evaluates threshold condition C (greater than 0.5s). The duration for: 5m ensures transient spikes do not generate alert fatigue, while noDataState: NoData and execErrState: Alerting enforce deterministic failure semantics.
apiVersion: 1
contactPoints:
- orgId: 1
name: oncall-slack-webhook
receivers:
- uid: slack-critical-ops
type: slack
settings:
url: '${ALERT_WEBHOOK_URL}'
recipient: '#alerts-checkout'
title: '{{ template "slack.default.title" . }}'
text: '{{ template "slack.default.text" . }}'
disableResolveMessage: false
policies:
- orgId: 1
receiver: oncall-slack-webhook
group_by: ['alertname', 'cluster', 'service']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- receiver: oncall-slack-webhook
matchers:
- severity = criticalSecret values must never be stored in plain text in Git. Grafana supports environment variable interpolation inside provisioning files: ${ALERT_WEBHOOK_URL} resolves from the process environment or Docker/K8s secret mount at boot. The notification policy groups alerts by service and cluster, suppressing duplicate pager notifications.
# 1. Inspect provisioned rule provenance and UI lock badge via API
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
"http://localhost:3000/api/v1/provisioning/alert-rules/checkout_p99_latency_slo" | jq '{uid: .uid, title: .title, provenance: .provenance}'
# 2. Dry-run evaluate condition expressions via API without firing live notifications
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3000/api/v1/eval" \
-d '{
"data": [
{"refId":"A","datasourceUid":"prometheus-prod","model":{"expr":"vector(0.62)","instant":true}},
{"refId":"B","datasourceUid":"__expr__","model":{"type":"reduce","reducer":"last","expression":"A"}},
{"refId":"C","datasourceUid":"__expr__","model":{"type":"threshold","expression":"B","conditions":[{"evaluator":{"params":[0.5],"type":"gt"}}]}}
],
"condition": "C"
}' | jq '{evaluation: .instances[0].evaluationState, value: .instances[0].values.B}'
# 3. Test contact point webhook receiver endpoint connectivity
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3000/api/v1/receivers/test" \
-d '{
"receivers": [
{"name":"test-slack","type":"slack","settings":{"url":"http://127.0.0.1:9099/test-webhook"}}
]
}' | jq .Correlated Observability: LogQL, TraceQL & Loki-to-Tempo Integration
Log analytics and distributed trace correlation. Assumptions: Grafana 11.3.1, Loki 3.0.0+, Tempo 2.6.0+, and OpenTelemetry instrumentation. See official Loki LogQL Guide, Loki Derived Fields, and Tempo TraceQL Syntax. Synthetic query examples; queries not run against live clusters.
LogQL extends Prometheus syntax to log streams. A stream selector isolates log streams by indexed labels (such as {app="checkout", env="production"}), pipeline stages parse and filter unstructured log lines, and metric aggregations compute error rates and latencies directly from logs without separate metrics instrumentation.
# 1. Stream filter + JSON parser + line filter + structured duration evaluation
{app="checkout", env="production"} |= "status=error" | json | latency_ms > 250
# 2. Metric aggregation: Error rate per second grouped by HTTP status over 5m window
sum by (status_code) (rate({app="checkout", env="production"} | json [5m]))
# 3. Log quantile calculation: P99 processing duration extracted from unstructured logs
quantile_over_time(0.99, {app="checkout"} | logfmt | unwrap duration_ms [10m]) by (region)In unified observability dashboards, seamless jumping from Loki logs to Tempo distributed traces is enabled via Loki Derived Fields. The datasource configuration defines a regular expression extracting the trace_id and renders a deep link into the Tempo datasource:
# /etc/grafana/provisioning/datasources/loki-tempo.yaml
apiVersion: 1
datasources:
- name: Loki
type: loki
uid: loki-prod
url: http://loki.monitoring.svc:3100
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '(?:trace_id|traceId)[=:"\']+([a-f0-9]+)'
url: '$${__value.raw}'
datasourceUid: 'tempo-prod'TraceQL queries traces structurally across root spans, child spans, and resource attributes:
# 1. Filter failing spans with latency over 500ms
{ span.http.status_code >= 500 && duration > 500ms }
# 2. Structural query: Gateway service failure caused by downstream billing slow span
{ resource.service.name = "gateway" && .status = error } >> { resource.service.name = "billing" && duration > 1s }| System | Failure Mode | Empty-Result Troubleshooting Action |
|---|---|---|
| Loki | Stream label mismatch | Verify label selector matches indexed chunks; avoid unindexed attributes in stream filter |
| Loki | JSON parser failure | Check for non-JSON lines breaking pipeline; insert | json after line filter |
| Tempo | Attribute scope prefix | Ensure span. vs resource. vs intrinsic .status prefix is correct |
| Tempo | Sampling drop | Check OpenTelemetry collector tail-sampling rules and retention compactor window |
Troubleshooting 09.5
No data or panels empty
Verify datasource config, query inspector, time range, and browser console for WebSocket errors.
Slow or expensive queries
Add recording rules in Prometheus. Increase $__interval. Use transformations to reduce data client-side.
Access Governance & Slow-Query Diagnostics: RBAC Boundaries & $__rate_interval
Production operations and performance diagnostics. Assumptions: Grafana >= 10.x / 11.x OSS vs Enterprise, Prometheus datasource. See official Grafana Roles and Permissions, Folder and Dashboard Access Control, and Grafana Query Optimization & Best Practices. Simulated diagnostics and offline benchmarks; no live infrastructure impact.
Grafana permission management differs significantly between editions. Grafana OSS enforces three organization-level roles: Admin, Editor, and Viewer. Access control is refined by assigning team or user permissions on folders (Permission levels: 1 = View, 2 = Edit, 4 = Admin), which recursively inherit down to child dashboards. Grafana Enterprise extends this with Fine-Grained Access Control (custom RBAC roles with targeted action scopes such as dashboards:read or datasources:query) and automated Team Sync from identity providers (LDAP, SAML, GitHub, Okta).
# 1. Audit current permissions on production billing folder (uid: f-prod-billing)
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
"http://localhost:3000/api/folders/f-prod-billing/permissions" | jq '.[] | {team: .teamTitle, role: .role, permission: .permissionName}'
# 2. Grant Editor (2) to Team 'billing-devs' (teamId: 5) and Viewer (1) to Org Viewers
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3000/api/folders/f-prod-billing/permissions" \
-d '{
"items": [
{"teamId": 5, "permission": 2},
{"role": "Viewer", "permission": 1}
]
}' | jq .When dashboard panels load sluggishly or timeout, open panel Query Inspector → Stats to analyze executionTimeMs, query bytes, and series counts. A primary anti-pattern is hardcoding rate intervals (e.g. [1m]) or relying naively on $__interval in PromQL queries. When users zoom out from 1 hour to 7 days, [1m] forces Prometheus to process hundreds of thousands of raw chunks, while $__interval can fall below the scrape interval and produce gaps. The dynamic variable $__rate_interval automatically calculates max($__interval + scrape_interval, 4 * scrape_interval), ensuring at least four data points exist in every rate window regardless of time zoom.
# /etc/prometheus/rules/checkout-recording.rules.yaml
groups:
- name: checkout-service-recording
interval: 30s
rules:
- record: job:http_request_duration_seconds:p99
expr: histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket{job="checkout"}[2m])) by (le, job))
- record: job:http_requests:rate5m
expr: sum(rate(http_requests_total{job="checkout"}[5m])) by (job, status)For high-traffic dashboards viewed by entire engineering organizations, offload real-time quantile calculations into Prometheus recording rules. Querying the precomputed metric job:http_request_duration_seconds:p99{job="checkout"} in Grafana reduces dashboard panel execution from 4500ms to 12ms.
# Simulated query execution profiling and permission recovery workflow
# Step 1: Profile expensive query latency via datasource query endpoint
curl -s -u "admin:${GRAFANA_ADMIN_PASSWORD}" \
-H "Content-Type: application/json" \
-X POST "http://localhost:3000/api/ds/query" \
-d '{
"queries": [
{
"refId": "A",
"datasource": {"uid": "prometheus-prod"},
"expr": "sum(rate(http_requests_total[1m])) by (handler, status)",
"range": true,
"intervalMs": 15000,
"maxDataPoints": 1000
}
],
"from": "now-6h",
"to": "now"
}' | jq '{latency_ms: .results.A.frames[0].schema.meta.custom.executedQueryString, series_count: (.results.A.frames | length)}'
# Step 2: Replace unoptimized range with dynamic $__rate_interval or precomputed recording rule
# Step 3: Verify dashboard response time drops below SLA (< 200ms)30-Day Roadmap 09.6
- Panel types
- Query editor
- JSON model basics
- Query variables
- Chained variables
- Repeat panels
- LogQL queries
- Promtail pipelines
- Log panels + derived fields
- Trace correlation
- Provisioning as code
- Multi-org / RBAC
Deep Dive: Provisioning & Advanced Observability 09.7
GitOps Dashboards
Store dashboard JSON in Git. Use dashboards.yaml to load them at startup. Never edit dashboards through the UI in production — treat them as code.
Trace + Log Correlation
Add trace IDs to logs. Use derived fields in Loki to jump from logs into Tempo traces. This dramatically speeds up debugging distributed systems.
Securing Grafana: Anonymous Access, Admin Secret and Viewer Role 09.8
Three defaults matter for a Grafana that holds production dashboards and datasource credentials: no anonymous access, no default admin/admin password, and people who only read dashboards get the Viewer role. Grafana reads any GF_<SECTION>_<KEY> environment variable as grafana.ini config, and a __FILE suffix reads the value from a file, which is how a Kubernetes or Docker secret is mounted.
Recorded from a real run of scripts/recordings/grafana.sh; every output below is pasted from scripts/recordings/grafana.out. Cover the output, predict it, then compare.
Environment: grafana/grafana:11.3.1 on Docker 26.1.5, published on 127.0.0.1 only, started with --env-file grafana.env and the admin password mounted at /run/secrets/admin_password (a demo value).
# Passed with --env-file. Grafana reads any GF_<SECTION>_<KEY> variable as grafana.ini config.
GF_AUTH_ANONYMOUS_ENABLED=false
GF_USERS_ALLOW_SIGN_UP=false
# __FILE: read the value from a mounted secret file instead of an env var or grafana.ini
GF_SECURITY_ADMIN_PASSWORD__FILE=/run/secrets/admin_password# Dashboard search with no credentials $ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/api/search 401 # The well-known default login $ curl -s -o /dev/null -w '%{http_code}\n' -u admin:admin http://localhost:3000/api/search 401 # The admin password from the secret file $ curl -s -u admin:"$(cat admin_password)" http://localhost:3000/api/org | jq -r .name Main Org. # Create a user through the admin API $ curl -s -u admin:"$(cat admin_password)" -H 'Content-Type: application/json' -d '{"name":"Ops Viewer","login":"viewer","password":"viewer-demo-pass"}' http://localhost:3000/api/admin/users | jq -r .message User created # Which role does a new user get in the main org? $ curl -s -u viewer:viewer-demo-pass http://localhost:3000/api/user/orgs | jq -r '.[0].role' Viewer # That user tries to save a dashboard $ curl -s -o /dev/null -w '%{http_code}\n' -u viewer:viewer-demo-pass -H 'Content-Type: application/json' -d '{"dashboard":{"title":"edit-test"}}' http://localhost:3000/api/dashboards/db 403
New users join the main org as Viewer by default (auto_assign_org_role), and a Viewer cannot save dashboards: 403. Datasource passwords and tokens belong in the datasource's secure fields or provisioning with environment variables, never in dashboard JSON that Viewers can export.