Skip to content
devops/architect
09 grafana 01 01 grafana dashboards & observability
0/8 read · lab 0/1
STARTUP TO ENTERPRISE
09 / 14 • DASHBOARDS & OBSERVABILITY

Grafana Dashboards & Observability

Build beautiful, actionable visualizations. Master variables, transformations, provisioning, Loki for logs, and Tempo for distributed tracing correlation.

Single Server RED Metrics Multi-tenant + GitOps

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.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

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.

graph TD G[Grafana] --> P[Prometheus] G --> L[Loki] G --> T[Tempo] subgraph Provisioning D[dashboards.yaml] DS[datasources.yaml] end

Core Components 09.2

FeaturePurposeExample
PanelsVisualizationsTime series, Stat, Gauge, Table
VariablesDynamic queries$__interval, $datasource
TransformationsPost-processingReduce, Join, Organize fields
ProvisioningGitOps dashboardsdashboards.yaml + git
Loki + TempoLogs + TracesLogQL, TraceQL correlation

WSL Hands-On Lab 09.3

Deploy Grafana + Loki + Promtail + Import Famous Dashboards

full stack
$ 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.

alerting/alert-rules.yaml
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-core

The 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.

alerting/contact-points.yaml
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 = critical

Secret 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.

alerting-api-validation.sh
# 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.

logql-queries.logql
# 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:

loki-derived-fields.yaml
# /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:

traceql-queries.traceql
# 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 }
SystemFailure ModeEmpty-Result Troubleshooting Action
LokiStream label mismatchVerify label selector matches indexed chunks; avoid unindexed attributes in stream filter
LokiJSON parser failureCheck for non-JSON lines breaking pipeline; insert | json after line filter
TempoAttribute scope prefixEnsure span. vs resource. vs intrinsic .status prefix is correct
TempoSampling dropCheck 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).

folder-permissions-api.sh
# 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.

prometheus-recording-rule.yaml
# /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.

slow-query-recovery-drill.sh
# 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

WEEK 1
Dashboard Fundamentals
  • Panel types
  • Query editor
  • JSON model basics
WEEK 2
Variables & Templating
  • Query variables
  • Chained variables
  • Repeat panels
WEEK 3
Loki Logging
  • LogQL queries
  • Promtail pipelines
  • Log panels + derived fields
WEEK 4
Tempo + Enterprise
  • 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).

grafana.env
# 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
recorded run
# 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.

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ curl -s -o /dev/null -w '%{http_code}\n' http://localhost:3000/api/search
Show the lesson's result

The lesson shows:

401

What result does the lesson show for this command?

$ curl -s -o /dev/null -w '%{http_code}\n' -u admin:admin http://localhost:3000/api/search
Show the lesson's result

The lesson shows:

401

What result does the lesson show for this command?

$ curl -s -u admin:"$(cat admin_password)" http://localhost:3000/api/org | jq -r .name
Show the lesson's result

The lesson shows:

Main Org.

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

The dashboard loaded fine. Every panel says No data.

Output recorded from a real run on grafana/grafana:12.1.1 and prom/prometheus:v3.5.0 containers on Docker Desktop, run from Git Bash on Windows. Grafana provisions its datasources and the Checkout dashboard from files, as the lesson recommends; G is localhost:13000 and query is a small shell helper that builds the panel's /api/ds/query request body for a given datasource uid. Timestamps vary per run. Nothing runs on your machine.

Builds on Troubleshooting.

The Checkout dashboard was built in the staging Grafana, exported to JSON and committed to Git. The production Grafana provisions it from that file. In production the "Targets up" panel shows No data, while the same JSON works in staging and Prometheus is scraping normally. Nobody has touched the panel query.

  1. Step 1 of 2: Prometheus is healthy and the query works in staging. What do you check first?

Design decision

Alert from Grafana, from Prometheus, or from both?

Builds on Core Components.

The team runs Prometheus with Alertmanager, Loki for logs and one Grafana instance. Metric alerts are Prometheus rules in Git, tested with promtool in CI. Two new alert needs have come up: a log alert on payment errors in Loki and an alert on an AWS SQS queue that exists only in CloudWatch. A developer proposes moving all alerting into Grafana so everything lives in one place.

Constraints

  • Grafana runs as a single instance with SQLite; Prometheus and Alertmanager run as HA pairs
  • On-call already routes, silences and groups through Alertmanager
  • Rules must stay in Git and be reviewed
  • The CloudWatch data is only reachable through Grafana's CloudWatch datasource today
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Run the first command shown in the section “WSL Hands-On Lab”
Run the first command shown in the section “WSL Hands-On Lab”

Ready. Type the command for the current goal.

Check yourself

How does Grafana govern alert rules and contact points provisioned from YAML files under /etc/grafana/provisioning/alerting/?

Explanation

In 'Real-World Project' under GitOps Alerting, 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.

What mechanism does Grafana use in a Loki datasource to enable seamless jumping from log lines to Tempo distributed traces?

Explanation

In 'Real-World Project' under Correlated Observability, seamless jumping from Loki logs to Tempo traces is enabled via Loki Derived Fields with a regex that extracts trace_id and deep links to the Tempo datasource.

Why does the lesson recommend using $__rate_interval instead of a hardcoded [1m] or naive $__interval in Grafana PromQL panels?

Explanation

In 'Troubleshooting' under Access Governance & Slow-Query Diagnostics, $__rate_interval calculates max($__interval + scrape_interval, 4 * scrape_interval) so at least four data points exist in every rate window without gaps or overload across zooms.

In a hardened Grafana setup where users are assigned the default Viewer role, what happens when a viewer attempts to save changes to a dashboard?

Explanation

In 'Securing Grafana: Anonymous Access, Admin Secret and Viewer Role', users assigned the Viewer role cannot save dashboards, receiving HTTP 403.

What are the three core organization-level roles in Grafana OSS?

Admin, Editor, and Viewer.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 3 sections Not covered Not covered Not covered
Operate Not covered Missing · 2 sections Not covered Not covered
Troubleshoot Not covered Not covered Missing · 1 section Not covered
Automate Not covered Not covered Missing · 1 section Not covered
Secure Not covered Not covered Not covered Not covered
Observe Not covered Missing · 2 sections Missing · 1 section Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Not covered Not covered

How this lesson fits each role