Prometheus & Grafana Hour 5: Automated Operations — Operator, GitOps and Monitoring as Code

Replace the approach of the first four hours, “hand-writing prometheus.yml and clicking dashboards in the UI”, with “everything in Git”: kube-prometheus-stack + Prometheus Operator declare scraping and rules with CRDs, Argo CD / Flux continuously reconcile the whole monitoring stack, Grafana data sources, dashboards and alerts are generated by ConfigMap / Terraform / Grafonnet, rules are unit-tested with promtool in CI, and blackbox exporter probes myapp from the user's perspective
kube-prometheus-stack 93.3.0Prometheus Operator v0.95.2Prometheus v3.16.0 · Alertmanager v0.35.0Grafana 13.3.1grafana provider v4.55.0blackbox_exporter v0.29.1Verified against official docs and GitHub Releases · 2026-11-15
Overall learning objectives
  • Explain the reconciliation mechanism of the Prometheus Operator: it watches Prometheus,ServiceMonitor,PodMonitor,Probe,ScrapeConfig,PrometheusRule and other CRDs, and selects objects by label selector matching, and generates prometheus.yaml.gz a Secret and rule ConfigMap, then config-reloader triggers /-/reload; and be able to troubleshoot independently why a ServiceMonitor was created but its target does not appear.
  • In the kind cluster lab in the monitoring namespace, install the release kps, and for the namespace myapp in the myapp (port 5000), write a ServiceMonitor and PrometheusRule with the release: kps label.
  • Use Helm + GitOps (Argo CD or Flux) to manage the monitoring stack itself: pin chart versions, layer values,CRD upgrades, Argo CD must use ServerSideApply=true,releaseName and the linkage with the selector.
  • Turn Grafana into code: the kps sidecar (grafana_dashboard: "1",grafana_datasource: "1", optional grafana_alert), file provisioning,Terraform grafana provider (folder / dashboard / contact point / notification policy / rule group) and Grafonnet (generating dashboard JSON with Jsonnet).
  • In CI, use promtool check rules + promtool test rules to write unit tests for alerts (input_series notation,alert_rule_test,promql_expr_test,--junit).
  • Use blackbox exporter + Probe CRDs for HTTP / TLS synthetic probing, and understand /probe?target=&module= ’s multi-target exporter pattern and relabeling, and write probe_success and certificate-expiry alerts.

Hour 1 time allocation table

#TimeModuleCore contentAnimation / interactionLab (kind cluster lab · namespaces monitoring / myapp)
0Before classPreparation: kind cluster and HelmReuse the kind cluster lab from the K8s course, Helm 4, the myapp:1.1 image (/metrics added in lesson 1), and the monitoring-config repository skeletonEnvironment self-check listDeploy myapp to namespace myapp
100–06kube-prometheus-stack and Prometheus Operatorchart composition, 10 CRDs, Operator pattern, control-plane targets on kind, generated object namesThe Operator expands the Prometheus CR into a StatefulSet / Secret / Servicehelm upgrade --install kps
206–13ServiceMonitor, PodMonitor and PrometheusRuleselector chain (Prometheus → ServiceMonitor → Service → EndpointSlice/Endpoints → Pod), named ports, PrometheusRule and admission webhook, ScrapeConfigCore animation: Operator reconciliation (including fault injection such as “label mismatch”)myapp ServiceMonitor + rules
313–21Managing the monitoring stack with Helm and GitOpsvalues layering, version pinning, CRD upgrades, Argo CD ServerSideApply, Flux crds policy, releaseName pitfallsGitOps sync simulator (Argo CD / Flux × 3 scenarios)Argo CD manages kps and monitoring-config
421–28Grafana provisioningfile provisioning vs sidecar, data source uid, dashboard ConfigMap, folder annotation, alert/contact point provisioning, UI read-onlythe sidecar loading dashboards process (failures can be injected)myapp RED dashboard ConfigMap
528–35Terraform Grafana provider and Grafonnetprovider authentication (service account token), folder/dashboard/contact_point/notification_policy/rule_group, Grafonnet and Foundation SDKTerraform plan drift simulationjsonnet generates dashboard → terraform apply
635–42Rule testing: promtool and CIcheck rules, test rules, series notation, eval_time, for and pending, GitHub ActionsAlert unit-test timeline (drag eval_time)Write tests for MyappDown / high error rate
742–50Black-box monitoring: blackbox exportermulti-target exporter pattern, modules, Probe CRD, relabel, probe_success, certificate expiryPhase breakdown of one probe (DNS / connection / TLS / HTTP)Install blackbox + Probe + alerts
850–60Recap, self-test and cleanup for the first five hoursKnowledge map of lessons 1–5, end-to-end monitoring-as-code pipeline, cleanup strategy (keep the cluster for lessons 6 and 7)End-to-end pipeline animation + interactive troubleshooting treeCleanup / keep
—After classCheat sheet · Comprehensive labFrom an empty cluster to a monitoring stack “all in Git”Final quiz (12 questions)Comprehensive lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Install and understand kube-prometheus-stack✓·✓····✓helm upgrade --install kpsM1 lab
Operator reconciliation and selector troubleshooting✓✓✓···✓✓kubectl get prometheus -o yamlM2 lab
ServiceMonitor / PodMonitor / Probe·✓····✓✓kubectl get servicemonitor -Amyapp, blackbox
PrometheusRule and rule validation·✓···✓✓✓promtool check rulesmyapp-rules
GitOps management of the monitoring stack and CRD upgrades··✓✓···✓argocd app sync,flux reconcile hrM3 lab
Grafana provisioning (sidecar / files)···✓✓··✓kubectl logs -c grafana-sc-dashboardRED dashboard
Terraform / Grafonnet managing Grafana···✓✓··✓jsonnet -J vendor,terraform planM5 lab
Rule unit tests and CI·✓✓··✓·✓promtool test rulesGitHub Actions
Black-box / synthetic probing·····✓✓✓curl …/probe?debug=trueProbe + alerts

What this course does not cover (and where to learn it)

TopicWhy it is not in this courseWhere to learn
Installation of Argo CD / Flux, detailed Application / HelmRelease fields, hooks and sync waves, remediationLesson 5 of the Helm course covers this systematically; this course only covers what is special about the “monitoring stack” chartHelm course lesson 5 (module 4 Argo CD, module 5 Flux)
Helm chart structure, values merging,helm upgrade parametersHelm course topicsHelm 8 hours
kind cluster creation, Service / EndpointSlice / label selector basics, RBACK8s course topicsKubernetes 8 hours
PromQL, alerting rule syntax, Alertmanager routingTopics from lessons 1 and 2 (used directly in this course)Lesson 1 · Lesson 2
Managed Prometheus / Grafana (Azure, AWS)Topics from lessons 3 and 4Lesson 3 · Lesson 4
Thanos / Mimir long-term storage, multi-cluster, SLO burn rateLesson 6 topics (reuse this course's kind environment)Lesson 6
Cardinality, TSDB, performance tuningLesson 7 topicsLesson 7
Grafana Operator, Crossplane, Terraform resources for Grafana CloudTime constraints; mentioned only in comparison tablesGrafana “as code” documentation

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. Read “Principles” and “Animation” first, then do the “Lab”. All labs in this course run on a local kind cluster with no cloud cost; module 3 needs a GitHub repository (free).
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
Voice narration
The “Voice” page reads the narration script aloud using the browser's built-in Web Speech API (en-US); if no Chinese voice pack is installed, you can read the narration script directly.
Version notes This course uses the baseline version verified on 2026-11-15: kube-prometheus-stack chart 93.3.0 (2026-11-13, appVersion = Prometheus Operator v0.95.2), whose default images are Prometheus v3.16.0, Alertmanager v0.35.0, Thanos v0.42.5; subchart dependency: grafana 14.4.1 (from oci://ghcr.io/grafana-community/helm-charts, appVersion Grafana 13.3.1, sidecar image kiwigrid/k8s-sidecar 2.14.3), kube-state-metrics 9.0.1, prometheus-node-exporter 5.1.0. prometheus-blackbox-exporter chart 11.21.3 (blackbox_exporter v0.29.1); Terraform grafana provider v4.55.0; Grafonnet has no version label (grafonnet-latest@main, officially marked as experimental and not officially supported). The cluster and tools follow the prerequisite courses: kind v0.33.0 (Kubernetes 1.37), Helm 4.3.x, Argo CD v3.6.1, Flux v2.10.0, Terraform 1.17.x. Note: This course was written against Grafana 13.3.1 (2026-11-10); the provisioning / sidecar / Terraform resources used here are the same in 12.x and 13.x.

Module 0 · Preparation: kind cluster and Helm (complete before class)

Reuse the kind cluster lab from the K8s course, deploy the myapp:1.1 image (with /metrics from lesson 1) to namespace myapp, and set up the monitoring-config repository skeleton; lessons 6 and 7 will continue to use this environment
Before class ≈ 20 minutesNo cloud costAt least 8 GB of memory recommended for Docker
Prerequisites
  • Complete this course Lesson 1 and Lesson 2: locally, the myapp in ~/promlab has already used prometheus_client to expose /metrics (gunicorn multiprocess mode uses PROMETHEUS_MULTIPROC_DIR), the image myapp:1.1 has been built; you have written prometheus/rules/*.yml alerting rules.
  • Unified metric names: myapp_http_requests_total{method,route,status} (counter),myapp_http_request_duration_seconds (histogram, buckets 0.005…5),myapp_redis_up (gauge).
  • Complete K8s course: have a kind cluster lab (1 control plane + 2 workers); complete the Helm course: familiar with Helm 4 and Argo CD / Flux.
  • Local tools: Docker, kind v0.33.0, kubectl 1.37, Helm 4.3.x, git, jq, yq (mikefarah v4), promtool (ships with the Prometheus release package), jsonnet (go-jsonnet) + jb, Terraform 1.17.x.

Costs, permissions and security risks

ResourceCostPermissions / risks
kind cluster lab + kube-prometheus-stackLocal, no costkps by default needs about 2–3 GB of memory (Prometheus, Grafana, Alertmanager, Operator, kube-state-metrics, and node-exporter on each node); node-exporter runs as hostNetwork/hostPID and mounts the host root filesystem read-only — suitable only for clusters you trust.
GitHub repository monitoring-configPublic or private repositories both work (the free Actions quota is sufficient)Do not commit the Grafana admin password, service account token or webhook URL to the repository; inject them via Secrets / CI secrets.
Grafana admin account—If kps does not set grafana.adminPassword , the grafana subchart generates a random password and stores it in the Secret kps-grafana ; do not expose port forwarding to the public internet after the lab.

Step 1: check tools and cluster

kind version
kubectl version --client
helm version --short
kind get clusters
kubectl config use-context kind-lab
kubectl get nodes -o wide
kind v0.33.0 go1.x linux/amd64
Client Version: v1.37.1
v4.3.2+g...
lab
Switched to context "kind-lab".
NAME                STATUS   ROLES           AGE   VERSION
lab-control-plane   Ready    control-plane   3d    v1.37.0
lab-worker          Ready    <none>          3d    v1.37.0
lab-worker2         Ready    <none>          3d    v1.37.0

If there is no cluster, rebuild it with the K8s course configuration: kind create cluster --name lab --config ~/k8slab/kind-lab.yaml (1 control plane + 2 workers). This course does not modify the kind configuration; kind's kube-controller-manager / scheduler / etcd / kube-proxy metrics only listen on 127.0.0.1, so module 1 disables scraping of these components in values (see module 1 principles).

Step 2: install the CLIs used in this course

# promtool: ships with the Prometheus release package (version should match the Prometheus in the cluster)
PROM_VER=3.16.0
curl -sLO https://github.com/prometheus/prometheus/releases/download/v${PROM_VER}/prometheus-${PROM_VER}.linux-amd64.tar.gz
tar xzf prometheus-${PROM_VER}.linux-amd64.tar.gz
sudo install prometheus-${PROM_VER}.linux-amd64/promtool /usr/local/bin/
promtool --version

# go-jsonnet and jsonnet-bundler (for Grafonnet)
go install github.com/google/go-jsonnet/cmd/jsonnet@latest
go install github.com/jsonnet-bundler/jsonnet-bundler/cmd/jb@latest

# yq (mikefarah v4)
sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 && sudo chmod +x /usr/local/bin/yq
promtool, version 3.16.0 (branch: HEAD, revision: ...)
  build user:       root@...
  go version:       go1.x

Step 3: deploy myapp to namespace myapp

The image comes from lesson 1 (myapp:1.1 with /metrics). kind nodes cannot pull local images, so first kind load:

kind load docker-image myapp:1.1 --name lab
mkdir -p ~/promlab/k8s && cd ~/promlab/k8s
apiVersion: v1
kind: Namespace
metadata:
  name: myapp
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  namespace: myapp
spec:
  replicas: 1
  selector:
    matchLabels: {app.kubernetes.io/name: redis}
  template:
    metadata:
      labels: {app.kubernetes.io/name: redis}
    spec:
      containers:
        - name: redis
          image: redis:7-alpine
          ports: [{containerPort: 6379, name: redis}]
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: myapp
spec:
  selector: {app.kubernetes.io/name: redis}
  ports: [{name: redis, port: 6379, targetPort: redis}]
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  namespace: myapp
spec:
  replicas: 2
  selector:
    matchLabels: {app.kubernetes.io/name: myapp}
  template:
    metadata:
      labels: {app.kubernetes.io/name: myapp}
    spec:
      containers:
        - name: myapp
          image: myapp:1.1
          imagePullPolicy: IfNotPresent
          ports:
            - name: http            # ← ServiceMonitor uses the “port name” rather than the port number
              containerPort: 5000
          env:
            - {name: REDIS_HOST, value: redis}
            - {name: PROMETHEUS_MULTIPROC_DIR, value: /tmp/prom}
          volumeMounts:
            - {name: prom-multiproc, mountPath: /tmp/prom}
          readinessProbe:
            httpGet: {path: /healthz, port: http}
          resources:
            requests: {cpu: 50m, memory: 64Mi}
            limits: {memory: 256Mi}
      volumes:
        - name: prom-multiproc
          emptyDir: {}            # .db files for multiprocess mode, cleared when the Pod restarts
---
apiVersion: v1
kind: Service
metadata:
  name: myapp
  namespace: myapp
  labels:
    app.kubernetes.io/name: myapp   # ← ServiceMonitor selects by the Service's labels
spec:
  selector: {app.kubernetes.io/name: myapp}
  ports:
    - name: http
      port: 5000
      targetPort: http
kubectl apply -f myapp.yaml
kubectl -n myapp rollout status deploy/myapp
kubectl -n myapp port-forward svc/myapp 5000:5000 &
curl -s localhost:5000/healthz; curl -s localhost:5000/ >/dev/null
curl -s localhost:5000/metrics | grep -E '^myapp_(http_requests_total|redis_up)' | head
deployment "myapp" successfully rolled out
ok
myapp_http_requests_total{method="GET",route="/",status="200"} 1.0
myapp_http_requests_total{method="GET",route="/healthz",status="200"} 3.0
myapp_redis_up 1.0

Step 4: create the monitoring-config repository skeleton

mkdir -p ~/promlab/monitoring-config && cd ~/promlab/monitoring-config
git init -b main
mkdir -p kps argocd flux manifests/myapp manifests/blackbox dashboards grafonnet terraform/grafana rules/tests .github/workflows
cp ~/promlab/k8s/myapp.yaml manifests/myapp/app.yaml
tree -a -I .git
.
├── .github/workflows/rules.yaml     ← Module 6: promtool CI (module 5 adds jsonnet / terraform checks)
├── kps/values.yaml                  ← Modules 1 and 3: kube-prometheus-stack values (single source of truth)
├── argocd/ or flux/                 ← Module 3: GitOps manifests (pick one)
├── manifests/
│   ├── myapp/                       ← application, ServiceMonitor, PrometheusRule (module 2)
│   └── blackbox/                    ← Probe and probe alerts (module 7)
├── dashboards/                      ← generated dashboard JSON + ConfigMaps (modules 4, 5)
├── grafonnet/                       ← Jsonnet source (module 5)
├── terraform/grafana/               ← folders / contact points / rule groups (module 5)
└── rules/tests/                     ← promtool unit tests (module 6)

Warm-up: answer from memory (30 seconds)

In lesson 1's prometheus.yml config, which section tells Prometheus “where to scrape”? After you change it, how does it take effect?

scrape_configs (static_configs or *_sd_configs + relabel_configs). It takes effect by sending SIGHUP, or through the HTTP reload endpoint if --web.enable-lifecycle is enabled POST /-/reload. This course shows the Operator generating the same scrape_configs, with config-reloader calling /-/reload on your behalf.

Why does the alert in lesson 2 need for: 2m?

The expression must stay true for 2 minutes before moving from pending to firing, filtering out transient flapping. Module 6 will use promtool to verify this on a timeline.

In the Helm course, can a release deployed by Argo CD be seen in helm list ?

No — Argo CD only uses helm template to render; Flux uses the Helm SDK to actually install, so the release can be seen. This affects how you judge what the “release label” means in this course.

Environment self-check list

Module 1 · kube-prometheus-stack and Prometheus Operator

00:00 – 06:00 · One chart installs the whole Kubernetes monitoring setup; the real work is done by the Operator: it expands CRDs into StatefulSets and configures Secrets and rule ConfigMaps
6 minchart 93.3.0 · Operator v0.95.2monitoring.coreos.com/v1 GA★★★★★
Learning objectives
  • List the components installed by kube-prometheus-stack (hereafter kps) and its 10 CRDs, and explain the division of labour between the chart, the Operator and the CRs.
  • Understand the Operator pattern: watch CRs → compute the desired state → create/update StatefulSets, Secrets, ConfigMaps and Services; know that Operator-generated objects must not be edited by hand.
  • On the kind cluster lab, install with the release name kps , and know which control-plane targets go DOWN on kind and how to turn them off.
  • Be able to derive all key object names from the release name (kps-kube-prometheus-stack-prometheus,kps-grafana …).
Prerequisites: K8s course Deployment / StatefulSet / Service / CRD; lesson 1's prometheus.yml. Importance:★★★★★

What: what kps is

kube-prometheus-stack is a Helm chart maintained by prometheus-community (formerly called the prometheus-operator chart); it bundles the kube-prometheus project's manifests, default alerting rules and Grafana dashboards. The chart's appVersion is the Prometheus Operator version (93.3.0 → v0.95.2); CRDs and the Operator version are strictly matched.

ComponentCreated byRoleName in lab (release = kps)
Prometheus Operatorchart (Deployment)watches CRDs and reconcileskps-kube-prometheus-stack-operator
Prometheuschart creates Prometheus CR → Operator creates StatefulSetscraping, storage, rule evaluationCR kps-kube-prometheus-stack-prometheus; Pod prometheus-kps-kube-prometheus-stack-prometheus-0
Alertmanagerchart creates Alertmanager CR → Operator creates StatefulSetgrouping, inhibition, notificationPod alertmanager-kps-kube-prometheus-stack-alertmanager-0
Grafanasubchart grafana 14.4.1 (Deployment)visualization; sidecar loads dashboards / data sourceskps-grafana (Service port 80)
kube-state-metricssubchartconverts K8s object state into metrics (kube_pod_status_phase …)kps-kube-state-metrics
node-exportersubchart (DaemonSet)node CPU / memory / disk / networkkps-prometheus-node-exporter
default rules and dashboardschart (PrometheusRule, ConfigMap)about 30 groups of kubernetes-mixin alerting and recording rules, dozens of dashboardskps-kube-prometheus-stack-*
ServiceMonitor (self-monitoring and K8s components)chartscrapes apiserver, kubelet/cAdvisor, coredns, and the above components themselveskubectl get servicemonitor -n monitoring

10 CRDs (API group monitoring.coreos.com): Prometheus,PrometheusAgent,Alertmanager,ThanosRuler (“workload” kinds; the Operator creates a StatefulSet for each); ServiceMonitor,PodMonitor,Probe,ScrapeConfig (v1alpha1),PrometheusRule,AlertmanagerConfig (v1alpha1) (“configuration” kinds; the Operator translates them into configuration files).

Why: why not write prometheus.yml directly

  • Configuration is declared in a distributed way alongside each application: application teams submit ServiceMonitor / PrometheusRule objects in their own namespaces, so the platform team does not have to maintain one huge central prometheus.yml.
  • Declarative and GitOps-friendly: every scrape job is a K8s object that can be kubectl apply, synced by Argo CD, governed by RBAC, and validated on admission.
  • Automation details: StatefulSets, storage, sharding, replicas, TLS, hot reload (config-reloader), and splitting rule files (ConfigMaps have a 1 MiB limit, so the Operator automatically splits them into rulefiles-0/1/…) are all handled by the Operator.
  • Works out of the box: kubernetes-mixin's rules and dashboards have been refined by the community over a long time, so you get node, Pod and apiserver alerts on day one.

How: the Operator reconciliation loop

  1. The Operator uses informers watch to watch all related CRs as well as Namespaces, Secrets, ConfigMaps and so on.
  2. Any change triggers a Prometheus CR's reconciliation loop.: it selects configuration objects based on its serviceMonitorSelector / serviceMonitorNamespaceSelector and similar selectors.
  3. Translate the selected objects into native Prometheus scrape_configs (one job per endpoint, named like serviceMonitor/myapp/myapp/0), gzipped and written to Secret prometheus-<CR name> 's prometheus.yaml.gz key; rules are written to ConfigMap prometheus-<CR name>-rulefiles-N.
  4. Ensure the StatefulSet exists with the correct spec (image, arguments, volumes, sidecars config-reloader).
  5. Inside the Pod, config-reloader watches the mounted files; after kubelet syncs the new Secret / ConfigMap content to the volume (usually tens of seconds to a minute or two), it decompresses /etc/prometheus/config_out/prometheus.env.yaml and POST /-/reload.

This is exactly what you did by hand in lesson 1 (edit the yml → reload); it has simply moved from a “person” to a “controller”. Conclusion: to change configuration, change the CR or values, not the Secret / StatefulSet—the Operator's next reconciliation overwrites hand edits.

When: when to use kps and when not to

OptionSuitable forNot suitable / notes
kube-prometheus-stack (this course)The de facto standard for self-managed K8s cluster monitoring; needs declarative CRD management, default rules and dashboardsMany components, high resource usage; major-version upgrades require manual CRD handling (module 3)
prometheus-community/prometheus chartDo not want an Operator; use prometheus.yml + annotation-based discoveryNo ServiceMonitor; scraping and rules all live in one ConfigMap
kube-prometheus (jsonnet)Needs deep customization and generates all manifests with jsonnetRequires mastering jsonnet; disconnected from the Helm ecosystem
Only install prometheus-operator (bundle.yaml)Only the CRDs and the Operator; you write the Prometheus CR yourselfNo default rules or dashboards
Managed services (AMP / Azure Monitor managed Prometheus)Do not want to run storage and high availability yourself (lessons 3 and 4)Azure uses its own CRD group azmonitoring.coreos.com, not fully interoperable with this course's CRDs
Common misconceptions① “kps will automatically scrape all Pods with prometheus.io/scrape annotations” — it will not; the Operator does not support annotation discovery, so you must write ServiceMonitor / PodMonitor (or write SD yourself with ScrapeConfig / additionalScrapeConfigs). ② “editing the Secret prometheus-… to temporarily add a job” — the Operator overwrites it immediately. ③ “helm upgrade will also upgrade CRDs” — Helm only creates the CRDs in the crds/ directory on first install and never upgrades them; kps's major-version upgrade notes require applying the CRDs manually first (module 3). ④ “Grafana is managed by the Operator” — Grafana is an ordinary subchart, unrelated to the Operator.

Architecture diagram: what kps consists of in the cluster

Namespace monitoring (helm release kps) Prometheus Operatorkps-kube-prometheus-stack-operatorwatch CRDs · reconcile CR (created by the chart) PrometheusAlertmanagerServiceMonitor × N (component self-monitoring)PrometheusRule × ~30+ your ServiceMonitor /PodMonitor / Probe / Rule watch StatefulSet prometheus-kps-… container prometheus :9090container config-reloader :8080volume: Secret prometheus.yaml.gzvolume: ConfigMap rulefiles-0 StatefulSet alertmanager-kps-…:9093 · config Secret …-generated create/update Grafana (subchart, not Operator)kps-grafana · sidecar loads dashboards kube-state-metricsK8s object state → metrics node-exporter (DaemonSet)each node :9100 apiserver · kubelet/cAdvisor · corednsscraped by the chart's ServiceMonitor disabled by default on kindcontroller-manager/scheduler/etcd/proxy data source uid=prometheus
Figure 1-1: the chart is responsible for “what gets installed”; the Operator is responsible for “turning CRs into running Prometheus / Alertmanager”

Expanded view: what objects one Prometheus CR becomes

Prometheus CRkps-kube-prometheus-stack-prometheus StatefulSet prometheus-kps-kube-prometheus-stack-prometheus (replicas, image, arguments) Secret prometheus-kps-kube-prometheus-stack-prometheus → key prometheus.yaml.gz ConfigMap prometheus-kps-kube-prometheus-stack-prometheus-rulefiles-0 (-1, -2 …) Secret …-tls-assets-0 · …-web-config (certificates and web configuration) Service prometheus-operated (headless, created by the Operator) · kps-kube-prometheus-stack-prometheus (created by the chart)
Figure 1-2: these objects' ownerReferences point to the CR: deleting the CR garbage-collects them; editing them by hand gets reverted at the next reconciliation

Animation: the Operator expands a Prometheus CR into a running Prometheus

Step through helm upgrade --install kps what happens in the cluster afterwards. Under each step is the corresponding real object, API call or log.

Click “Play” or “Next”.
$ # log

Core commands

CommandPurposeNotes
helm repo add prometheus-community https://prometheus-community.github.io/helm-chartsAdd the traditional HTTP repositoryOCI can also be used directly: oci://ghcr.io/prometheus-community/charts/kube-prometheus-stack (the official README's preferred option)
helm show values … --version 93.3.0Export default values (about 6000 lines)Write only the keys you want to change into your own values.yaml
helm upgrade --install kps … -n monitoring --create-namespace --version 93.3.0 -f kps/values.yamlInstall / upgradeThe release name determines all object names and selector labels release: kps
kubectl get crd | grep monitoring.coreos.comConfirm the 10 CRDsCRDs remain after the chart is uninstalled
kubectl -n monitoring get prometheus,alertmanagerList workload-type CRsShows VERSION / DESIRED / READY / RECONCILED / AVAILABLE
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operatorOperator logsSelector issues and the reasons invalid objects were rejected are recorded here

1. Write the values for the lab

## For the kind cluster lab only. Write only keys that differ from the defaults.
# kind's component metrics only listen on 127.0.0.1 and cannot be scraped → disable them to avoid *Down alert noise
kubeControllerManager: {enabled: false}
kubeScheduler: {enabled: false}
kubeEtcd: {enabled: false}
kubeProxy: {enabled: false}

prometheus:
  prometheusSpec:
    retention: 2d
    scrapeInterval: 30s
    resources:
      requests: {cpu: 200m, memory: 512Mi}
      limits: {memory: 1536Mi}
    # The following 4 stay at the default true: they only select ServiceMonitor / PodMonitor / Probe / PrometheusRule carrying the label release: kps
    serviceMonitorSelectorNilUsesHelmValues: true
    podMonitorSelectorNilUsesHelmValues: true
    probeSelectorNilUsesHelmValues: true
    ruleSelectorNilUsesHelmValues: true

alertmanager:
  alertmanagerSpec:
    resources:
      requests: {cpu: 20m, memory: 64Mi}

grafana:
  # Not setting adminPassword → the subchart generates a random password and stores it in Secret kps-grafana
  sidecar:
    dashboards:
      folderAnnotation: grafana_folder        # module 4: place dashboards into folders by annotation
      provider:
        foldersFromFilesStructure: true

2. Install

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update prometheus-community
helm upgrade --install kps prometheus-community/kube-prometheus-stack \
  -n monitoring --create-namespace \
  --version 93.3.0 \
  -f ~/promlab/monitoring-config/kps/values.yaml \
  --wait --timeout 10m
kubectl -n monitoring get pods
Release "kps" does not exist. Installing it now.
NAME: kps
NAMESPACE: monitoring
STATUS: deployed
REVISION: 1
NAME                                                     READY   STATUS    RESTARTS   AGE
alertmanager-kps-kube-prometheus-stack-alertmanager-0    2/2     Running   0          2m
kps-grafana-6d8f7c9b8-x2kqp                              3/3     Running   0          2m
kps-kube-prometheus-stack-operator-5b8c6d7f9d-qlz7m      1/1     Running   0          2m
kps-kube-state-metrics-7c9f8d6b5-hm2tr                   1/1     Running   0          2m
kps-prometheus-node-exporter-4xk2p                       1/1     Running   0          2m
kps-prometheus-node-exporter-9qwmz                       1/1     Running   0          2m
kps-prometheus-node-exporter-tq8vd                       1/1     Running   0          2m
prometheus-kps-kube-prometheus-stack-prometheus-0        2/2     Running   0          2m

How to verify: The Prometheus Pod is 2/2 (prometheus + config-reloader); Grafana is 3/3 (grafana + two sidecars: dashboards, datasources). Common mistakes: Forgetting -n monitoring and installing into default; using a different release name (such as monitoring) causes every later release: kps label to fail to match. Production use: Pin --version the version, keep values in Git, and apply them through GitOps (module 3).

3. See what the Operator generated

kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}{.spec.ruleSelector}{"\n"}'
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -E '^- job_name' | head
kubectl -n monitoring get cm -l prometheus-name=kps-kube-prometheus-stack-prometheus
{"matchLabels":{"release":"kps"}}
{"matchLabels":{"release":"kps"}}
- job_name: serviceMonitor/monitoring/kps-kube-prometheus-stack-alertmanager/0
- job_name: serviceMonitor/monitoring/kps-kube-prometheus-stack-apiserver/0
- job_name: serviceMonitor/monitoring/kps-kube-prometheus-stack-coredns/0
- job_name: serviceMonitor/monitoring/kps-kube-prometheus-stack-kubelet/0
- job_name: serviceMonitor/monitoring/kps-kube-prometheus-stack-kubelet/1
...
NAME                                                     DATA   AGE
prometheus-kps-kube-prometheus-stack-prometheus-rulefiles-0   30     3m

This group of commands is the most important troubleshooting toolkit in this course: What the CR's selector is → whether my job appears in the generated configuration.

4. Access the UI

kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090:9090 &
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-alertmanager 9093:9093 &
kubectl -n monitoring port-forward svc/kps-grafana 3000:80 &
kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d; echo

Grafana username admin. Open http://localhost:9090/targets, on kind everything should be UP (because 4 control-plane target groups were turned off).

Goal In the kind cluster lab, install kps, confirm the components, CRDs and generated configuration, and understand that “hand edits get reverted”. Environment: module 0 complete; no cloud cost.
Install: following steps 1 and 2 on the “Command” page, write the values and install, then wait for all Pods to be Running.
kubectl get crd -o name | grep monitoring.coreos.com | wc -l
kubectl -n monitoring get prometheus
10
NAME                                   VERSION   DESIRED   READY   RECONCILED   AVAILABLE   AGE
kps-kube-prometheus-stack-prometheus   v3.16.0   1         1       True         True        4m
Inspect generated configuration: run step 3 on the “Command” page, count the jobs, and find the two kubelet jobs (/0 is kubelet itself,/1 is cAdvisor).
Verify that hand edits are reverted: scale the StatefulSet replicas to 0 and observe the Operator change it back to 1.
kubectl -n monitoring scale sts prometheus-kps-kube-prometheus-stack-prometheus --replicas=0
sleep 10; kubectl -n monitoring get sts prometheus-kps-kube-prometheus-stack-prometheus
NAME                                              READY   AGE
prometheus-kps-kube-prometheus-stack-prometheus   1/1     6m

Correct approach: in values, change the prometheus.prometheusSpec.replicas and then run helm upgrade (or change the CR).

Confirm default rules: in the Prometheus UI → Alerts, you can see Watchdog is firing (it is a “dead man's switch” that always fires and is used to verify that the alert pipeline works).
Verify: http://localhost:9090/targets all UP; in Grafana the “Kubernetes / Compute Resources / Cluster” dashboard shows data.
Cleanup: nothing to clean up in this module — modules 2–8 and lessons 6 and 7 all continue on this kps install.

Case 1: “control-plane targets permanently DOWN” on managed K8s

Problem: On AKS / EKS, copying the default values as-is leads to persistent KubeControllerManagerDown and KubeSchedulerDown alerts. Approach: Managed control planes do not expose metrics endpoints for these components, so directly disable kubeControllerManager.enabled=false etc.; use the cloud vendor's control-plane metrics when needed (lessons 3 and 4). kind is the same, except the reason is that the components bind to 127.0.0.1. Limitations: You lose alerting on these components, so compensate with apiserver metrics and cloud monitoring.

Case 2: multiple Prometheus instances in one cluster

Problem: The platform team's kps and a business team's self-installed Prometheus Operator compete over ServiceMonitors. Approach: Install only one Operator per cluster (multiple Operators will all reconcile the same CRDs); when you need multiple Prometheus instances, use multiple Prometheus CRs with different selectors (such as prometheus: team-a) to isolate them under one Operator; or use the Operator's --namespaces / instance sharding parameters. Configuration: Change the business team's ServiceMonitor label to prometheus: team-a, the same as the corresponding CR's serviceMonitorSelector.matchLabels .

Case 3: Prometheus gets OOMKilled

Problem: The default resources: {}, under node memory pressure Prometheus is evicted, and WAL replay exhausts memory again. Approach: Estimate requests/limits from “active series count × memory per series” and set them, and enable a persistent volume storageSpec.volumeClaimTemplate; lesson 7 covers cardinality and head block memory in depth.

Common errors and fixes

Error: INSTALLATION FAILED: unable to build kubernetes objects from release manifest: resource mapping not found for name: "kps-…" kind: "Prometheus" … ensure CRDs are installed first

Cause: Installed with --skip-crds or crds.enabled=false, but the CRDs are not present in the cluster; or with GitOps the CRDs and CRs are in the same sync but the CRDs were not created first.

kubectl get crd prometheuses.monitoring.coreos.com
helm show crds prometheus-community/kube-prometheus-stack --version 93.3.0 | kubectl apply --server-side -f -

Fix: Install the CRDs first; with Argo CD use sync waves / SkipDryRunOnMissingResource=true (module 3).

KubeControllerManagerDown / KubeSchedulerDown / etcdInsufficientMembers firing persistently (kind / managed cluster)

Cause: These components' metrics endpoints are unreachable (kind binds to 127.0.0.1; managed clusters do not expose them).

kubectl -n kube-system get pods -l component=kube-controller-manager -o yaml | grep -- --bind-address

Fix: In values, set kubeControllerManager.enabled=false to false, etc.; or (on a self-managed cluster) change bind-address to the node IP and put proper network access controls in place.

prometheus-kps-…-0 stays Pending: 0/3 nodes are available: 3 Insufficient memory

Cause: requests are too large, or Docker has insufficient memory for kind.

kubectl -n monitoring describe pod prometheus-kps-kube-prometheus-stack-prometheus-0 | tail -5
kubectl top nodes

Fix: Lower requests or give Docker Desktop more memory; in the lab you can disable non-essential components other than alertmanager.enabled (not recommended to disable kube-state-metrics).

Grafana login shows Invalid username or password

Cause: The password is randomly generated; or when upgrading you changed adminPassword but the Grafana database (PVC) still has the old password — Grafana only uses that value when it first initializes the database.

kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d; echo
kubectl -n monitoring exec deploy/kps-grafana -c grafana -- grafana cli admin reset-admin-password '<new password>'
Command-line exercise
1. Without opening the UI, list all job names in the currently generated Prometheus configuration.
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | yq '.scrape_configs[].job_name'
2. Check the Prometheus image tag that kps 93.3.0 uses by default.
helm show values prometheus-community/kube-prometheus-stack --version 93.3.0 | yq '.prometheus.prometheusSpec.image'

Expected tag: v3.16.0-distroless (example; follow the actual output).

Scenario analysis question
A colleague says: “I changed the Prometheus StatefulSet memory limit from 1.5Gi to 4Gi, and after a while it changed back — did Helm roll it back?” Explain and give the correct approach.

No, it is the Operator, not Helm: the StatefulSet is generated from the Prometheus CR, and at each reconciliation the Operator restores it to the desired value in the CR. The correct approach is to change prometheus.prometheusSpec.resources (values) and then helm upgrade, or commit the change in the GitOps repository. Likewise, the configuration Secret and the rule ConfigMaps must not be edited by hand.

Verified teaching videos

▶
Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1 — TechWorld with Nana
English · Installing kps and Operator concepts with Helm (recorded earlier; chart versions and object names follow this course)
▶
Introduction to the Prometheus Operator on Kubernetes — That DevOps Guy
English · How the Operator and CRDs work

Official documentation

Video storyboard script (about 70 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–20s
Scene: a terminal runs helm upgrade --install kps; the camera pulls back and blocks representing the Operator, Grafana, node-exporter and so on appear in the cluster.
Narration: one chart installs the whole monitoring stack, but the chart itself does not create Prometheus directly.
Shot 2 · 20–45s
Scene: a card labelled “Prometheus CR” is read by the Operator and expands into four blocks: StatefulSet, configuration Secret, rule ConfigMap, Service.
Narration: the Operator reads the CR and generates all the objects needed to run Prometheus.
Shot 3 · 45–70s
Scene: someone manually changes the StatefulSet replicas to 0; a few seconds later it is changed back to 1 automatically, and the screen shows “change the CR, not the generated objects”.
Narration: generated objects are continuously reconciled by the controller; to change them, change values or the CR.
or score ≥ 70% in the “Quiz”

Module 2 · ServiceMonitor, PodMonitor and PrometheusRule

06:00 – 13:00 · A four-level selector chain decides whether a target appears: Prometheus → ServiceMonitor → Service → Endpoints/EndpointSlice → the Pod's named port; rules follow the same logic via ruleSelector
7 minmonitoring.coreos.com/v1 (GA)ScrapeConfig is v1alpha1★★★★★
Learning objectives
  • Write a ServiceMonitor for myapp (release: kps, named ports http, namespaceSelector), and know when to use PodMonitor, Probe or ScrapeConfig instead.
  • Explain the selector chain level by level, and use 3 commands to locate the break when a “target does not appear”.
  • Rewrite the lesson 2 alert as a PrometheusRule, and understand admission webhook validation, the rulefiles ConfigMap and hot reloading.
Prerequisites: Module 1; the Service and label selectors from the K8s course; the alerts from lesson 2. Importance:★★★★★

What: four kinds of “scrape configuration” CRDs

CRDSelectsGenerated SDTypical use
ServiceMonitorLabelled Service, scrapes each Pod through the Service's endpoints (Endpoints / EndpointSlice)kubernetes_sd_configs role endpoints (or endpointslice, determined by serviceDiscoveryRole )Most applications with a Service: myapp, redis-exporter
PodMonitorLabelled Pod (no Service needed)role podJobs / DaemonSet sidecars without a Service, ports used only for metrics
ProbeA static URL or Ingress, probed through the prober (blackbox exporter)static / ingress SD + relabel to /probeblack-box probing (module 7)
ScrapeConfig (v1alpha1)Almost any Prometheus SD: static, file, http, DNS, consul, EC2, Azure …Close to native configurationTargets outside the cluster, replacing additionalScrapeConfigs

There is only one kind of rule: PrometheusRule (spec.groups is the same as the native rule file's groups format, fully isomorphic), selected by the Prometheus CR's ruleSelector / ruleNamespaceSelector selection.

Why: why there are two layers of selection

The first layer (Prometheus → ServiceMonitor) lets the platform team decide which monitoring declarations this Prometheus accepts (kps defaults to release: kps); the second layer (ServiceMonitor → Service) lets the application team decide which services, ports and intervals to scrape. In multi-tenant setups you can also use namespaceSelector to isolate tenants. The trade-off is: any mismatch at any layer produces no error; the result is simply “nothing happens”—this is the most common point of confusion for Operator newcomers.

How: step-by-step check of the selector chain

#Who selects whomFieldmyapp's valueSymptom when mismatched
①Prometheus CR → namespace of ServiceMonitorserviceMonitorNamespaceSelector{} = all namespacesjob does not appear in configuration
②Prometheus CR → ServiceMonitor labelsserviceMonitorSelectorrelease: kpsjob does not appear in configuration (most common)
③ServiceMonitor → namespace of Servicespec.namespaceSelectormatchNames: [myapp] (if omitted = the ServiceMonitor's own namespace)job exists, target 0/0
④ServiceMonitor → Service labelsspec.selectorapp.kubernetes.io/name: myapp (labels on Service , not on the Pod)job exists, target 0/0
⑤endpoint → Service portendpoints[].port (port name) or targetPorthttpjob exists, target 0/0
⑥Service → PodService spec.selector and readiness statusWhen a Pod is not ready, its address goes into notReadyAddressestarget count less than replicas

Generated job name looks like serviceMonitor/<namespace>/<name>/<endpoint index>, the target's job label defaults to the Service name (can be changed via jobLabel ) to a Service label value, and automatically adds the namespace,service,pod,container,endpoint labels.

PrometheusRule path: apply → admission webhook (enabled by default in kps, validates PromQL syntax) → the Operator selects by ruleSelector → written to ConfigMap prometheus-…-rulefiles-0 (file name <namespace>-<name>-<uid>.yaml) → kubelet syncs the volume → config-reloader triggers reload → appears on the Rules page.

When: which one to choose

  • With a Service: ServiceMonitor (most Helm charts have a built-in switch serviceMonitor.enabled, be sure to add the release: kps label to it — usually serviceMonitor.additionalLabels or labels).
  • No Service, or flexible selection by Pod annotations / labels: PodMonitor.
  • Targets outside the cluster (VMs, SaaS), requiring file / http / DNS SD: ScrapeConfig.
  • Black-box probing: Probe.
  • To make kps select all ServiceMonitors (ignoring labels): serviceMonitorSelectorNilUsesHelmValues: false (fine for a single-tenant lab; not recommended for multi-tenant production).
Common misconceptions① “release: kps must go on the Service”—wrong; it goes on ServiceMonitor ; what the Service needs is the labels that the ServiceMonitor spec.selector specifies. ② “port: 5000”——endpoints[].port is the Service port's name; when it is only a number, use targetPort. ③ “ServiceMonitor selects Pod labels”—no, it selects Service labels; the Pod is selected by the Service's own selector. ④ “PrometheusRule is also validated by the Operator for whether “for” is reasonable”—the webhook only checks syntax; logical correctness relies on the module 6 unit tests.

selector chain: from Prometheus CR to the Pod port

Prometheus CRserviceMonitorSelector:release: kps ①②NamespaceSelector: {}ns monitoring ServiceMonitor myapplabels: release: kpsnamespaceSelector: myapp ③selector: name=myapp ④endpoints: port: http ⑤ Service myapplabels: name=myappports: name http 5000selector: name=myapp ⑥ns myapp Pod myapp-…-a10.244.1.7:5000 http Pod myapp-…-b10.244.2.5:5000 http ①② mismatch: the job is not generated at allThe Operator reports no error; serviceMonitor/myapp/myapp/0 cannot be found in /configCheck: kubectl get prometheus -o jsonpath='{.spec.serviceMonitorSelector}'Fix: add labels.release: kps to the ServiceMonitor ③④⑤ mismatch: job exists but 0/0 upthe relabel keep rule drops all endpointsCheck: “serviceMonitor/myapp/myapp/0 (0/0 up)” on /targetsFix: compare against the Service's labels and port names
Figure 2-1: two-layer selection: the platform chooses “monitoring declarations”, declarations choose “services and ports”; where the break occurs determines the symptom

Data flow: PrometheusRule from apply to effective

kubectl applyPrometheusRule admission webhookPromQL syntax validation OperatorruleSelector match ConfigMap…-rulefiles-0 kubeletvolume sync ~60s reloaderPOST /-/reload Syntax error → apply is rejected directlyLabel mismatch → silently ignoredDuring this period the old rules keep running
Figure 2-2: rules and scrape configs follow the same “generate file → volume sync → hot reload” path

Core animation: the Operator reconciles ServiceMonitor → generates scrape configuration → config-reloader → target appears

Choose a scenario (including the classic “label mismatch”), then play to watch each step's components and the real API / file / HTTP calls. The highlighted box shows the current step; red shows where the chain breaks.

kubectl applyServiceMonitor kube-apiserveretcd persistence Operatorinformer event selector matchrelease / namespace generated configurationscrape_configs Secret/CMprometheus.yaml.gz kubeletsync volume file config-reloaderPOST /-/reload Prometheus SDwatch endpoints + relabel /targetstarget UP Note: red box = the chain breaks here; when ①② break, the Operator records no error; when ③④⑤ break, the job exists but is 0/0 up. Current scenario: normal
Select a scenario, then click “Play”.
$ # log

Core commands

CommandPurposeNotes
kubectl get servicemonitor,podmonitor,probe,prometheusrule -AList all monitoring declarationsshort name smon,pmon,promrule
kubectl get smon -A -l release=kpslist only the ones kps will selectCompare with the CR's selector
kubectl -n myapp get svc myapp --show-labelsCheck ④the labels the ServiceMonitor selects by
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp -o wideCheck ⑤⑥port name and ready addresses
curl -s localhost:9090/api/v1/targets?state=active | jq …Query targets via the APImore suitable for scripting than the UI
curl -s localhost:9090/api/v1/rules | jq …Confirm the rules are loadedfilter by group name

1. myapp's ServiceMonitor

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: myapp
  namespace: myapp
  labels:
    release: kps                 # ② the key to being selected by kps's Prometheus
spec:
  namespaceSelector:
    matchNames: [myapp]          # ③ if omitted, defaults to this ServiceMonitor's own namespace
  selector:
    matchLabels:
      app.kubernetes.io/name: myapp   # ④ the Service's label
  endpoints:
    - port: http                 # ⑤ the name of the Service port
      path: /metrics
      interval: 30s
      scrapeTimeout: 10s
      metricRelabelings:         # after scraping, before ingestion: drop unneeded series (detailed in lesson 7)
        - sourceLabels: [__name__]
          regex: 'python_gc_.*'
          action: drop
kubectl apply -f manifests/myapp/servicemonitor.yaml
# Wait for kubelet sync + reload (usually < 2 minutes)
curl -s 'localhost:9090/api/v1/targets?state=active' | jq -r '.data.activeTargets[] | select(.labels.namespace=="myapp") | [.scrapePool,.labels.job,.labels.pod,.health] | @tsv'
servicemonitor.monitoring.coreos.com/myapp created
serviceMonitor/myapp/myapp/0	myapp	myapp-7d9c8b6f5-2xq8r	up
serviceMonitor/myapp/myapp/0	myapp	myapp-7d9c8b6f5-k4m9t	up

2. View the job generated by the Operator (excerpt)

kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip \
  | yq '.scrape_configs[] | select(.job_name == "serviceMonitor/myapp/myapp/0")'
job_name: serviceMonitor/myapp/myapp/0
honor_labels: false
kubernetes_sd_configs:
  - role: endpoints          # if the Prometheus CR sets serviceDiscoveryRole: EndpointSlice, this becomes endpointslice
    namespaces:
      names: [myapp]
scrape_interval: 30s
scrape_timeout: 10s
metrics_path: /metrics
relabel_configs:
  - action: keep             # ④ Service label
    source_labels: [__meta_kubernetes_service_label_app_kubernetes_io_name, __meta_kubernetes_service_labelpresent_app_kubernetes_io_name]
    regex: (myapp);true
  - action: keep             # ⑤ port name
    source_labels: [__meta_kubernetes_endpoint_port_name]
    regex: http
  - source_labels: [__meta_kubernetes_namespace]
    target_label: namespace
  - source_labels: [__meta_kubernetes_service_name]
    target_label: job        # job label defaults to the Service name
  ...
metric_relabel_configs:
  - source_labels: [__name__]
    regex: python_gc_.*
    action: drop

This is the kubernetes_sd_configs + relabel_configs you wrote by hand in lesson 1, except that the Operator generates it from the CRD. Once you understand this, you can explain why the job still exists but has no targets when ④ or ⑤ is wrong.

3. PrometheusRule: move the lesson 2 rules into the cluster

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: myapp-rules
  namespace: myapp
  labels:
    release: kps                 # selected by ruleSelector
spec:
  groups:
    - name: myapp.recording
      interval: 30s
      rules:
        - record: myapp:http_requests:rate5m
          expr: sum by (namespace, route, status) (rate(myapp_http_requests_total[5m]))
        - record: myapp:http_request_duration_seconds:p95_5m
          expr: histogram_quantile(0.95, sum by (namespace, le) (rate(myapp_http_request_duration_seconds_bucket[5m])))
    - name: myapp.alerts
      rules:
        - alert: MyappTargetMissing
          expr: absent(up{namespace="myapp", job="myapp"})
          for: 5m
          labels: {severity: critical}
          annotations:
            summary: "myapp has no scrape targets"
            description: "Check the ServiceMonitor release label and selector (module 2)."
        - alert: MyappDown
          expr: up{namespace="myapp", job="myapp"} == 0
          for: 2m
          labels: {severity: critical}
          annotations:
            summary: "myapp instance {{ $labels.pod }} scrape failed"
        - alert: MyappHighErrorRate
          expr: |
            sum by (namespace) (rate(myapp_http_requests_total{namespace="myapp", status=~"5.."}[5m]))
              /
            sum by (namespace) (rate(myapp_http_requests_total{namespace="myapp"}[5m])) > 0.05
          for: 5m
          labels: {severity: warning}
          annotations:
            summary: "myapp 5xx ratio {{ $value | humanizePercentage }}"
        - alert: MyappRedisDown
          expr: myapp_redis_up{namespace="myapp"} == 0
          for: 1m
          labels: {severity: critical}
          annotations:
            summary: "myapp cannot connect to Redis ({{ $labels.pod }})"
        - alert: MyappHighLatencyP95
          expr: myapp:http_request_duration_seconds:p95_5m{namespace="myapp"} > 0.5
          for: 10m
          labels: {severity: warning}
          annotations:
            summary: "myapp P95 latency {{ $value | humanizeDuration }}"
kubectl apply -f manifests/myapp/prometheusrule.yaml
kubectl -n monitoring get cm prometheus-kps-kube-prometheus-stack-prometheus-rulefiles-0 -o json | jq -r '.data | keys[]' | grep myapp
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[] | select(.name|startswith("myapp")) | .name + " " + (.rules|length|tostring)'
prometheusrule.monitoring.coreos.com/myapp-rules created
myapp-myapp-rules-1f2e3d4c-5b6a-4789-9abc-0d1e2f3a4b5c.yaml
myapp.recording 2
myapp.alerts 5

Note: The > in YAML is already escaped on the HTML page; after copying it becomes a plain >. MyappTargetMissing Use absent() as a fallback for “no data at all because of a selector mismatch” — without it,MyappDown never fires, because no up series exist at all.

4. PodMonitor and ScrapeConfig examples

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: myapp-worker
  namespace: myapp
  labels: {release: kps}
spec:
  selector:
    matchLabels: {app.kubernetes.io/name: myapp-worker}
  podMetricsEndpoints:
    - port: metrics            # name of the Pod container port
      interval: 30s
apiVersion: monitoring.coreos.com/v1alpha1
kind: ScrapeConfig
metadata:
  name: legacy-vms
  namespace: monitoring
  labels: {release: kps}       # kps's scrapeConfigSelector also requires the release label by default
spec:
  staticConfigs:
    - targets: ["10.0.0.11:9100", "10.0.0.12:9100"]
      labels: {env: lab}
  metricsPath: /metrics
Goal: make myapp appear on /targets, and deliberately create, locate and fix a “label mismatch”. Environment: the kps from module 1; myapp in namespace myapp.
Deliberately write it wrong: first apply a release: prometheus version (as many older tutorials do).
sed 's/release: kps/release: prometheus/' manifests/myapp/servicemonitor.yaml | kubectl apply -f -
sleep 90
curl -s localhost:9090/api/v1/targets | jq '[.data.activeTargets[] | select(.labels.namespace=="myapp")] | length'
servicemonitor.monitoring.coreos.com/myapp created
0
Locate in three steps:
# ① What label does Prometheus require?
kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}'
# ② What labels does my ServiceMonitor have?
kubectl -n myapp get smon myapp --show-labels
# ③ Does this job appear in the generated configuration?
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep -c 'serviceMonitor/myapp/'
{"matchLabels":{"release":"kps"}}
NAME    AGE   LABELS
myapp   2m    release=prometheus
0
Fix: kubectl apply -f manifests/myapp/servicemonitor.yaml (release: kps); after about 1–2 minutes the target appears and both Pods are up.
Create another “0/0 up”: change port: http to port: metrics, confirm that /targets shows serviceMonitor/myapp/myapp/0 (0/0 up), then change it back.
Rules: apply the PrometheusRule; in Prometheus UI → Alerts you see 5 myapp alerts (inactive); scale the redis Deployment to 0, and after about 1–2 minutes MyappRedisDown goes pending → firing, then restore it.
kubectl -n myapp scale deploy redis --replicas=0
# Observe the Alerts page …
kubectl -n myapp scale deploy redis --replicas=1
Commit to Git: git add manifests/myapp && git commit -m "feat: myapp ServiceMonitor and rules". Module 3 will have Argo CD take over these files.

Case 1: a ServiceMonitor from a third-party chart never takes effect

Problem: An ingress controller chart has enabled metrics.serviceMonitor.enabled=true, but no target appears. Approach: The ServiceMonitor generated by that chart does not have release: kps; add it via its metrics.serviceMonitor.additionalLabels (key names differ between charts). The platform team states in the docs “the only convention for onboarding to monitoring: release: kps”, and uses a Kyverno/Gatekeeper policy to warn when a ServiceMonitor lacks that label. Limitation: Field names differ between charts, so each one must be checked individually.

Case 2: multi-tenant isolation

Problem: Team A's ServiceMonitor, via namespaceSelector.any: true , scraped team B's services. Approach: Create one Prometheus CR per tenant (or a PrometheusAgent), using serviceMonitorNamespaceSelector to select only that tenant's namespaces; set ignoreNamespaceSelectors: true on the Prometheus CR so that ServiceMonitors can only discover targets in their own namespace; when necessary, enforcedNamespaceLabel: namespace to enforce a namespace label on all series and rules.

Case 3: a wrong rule breaks the whole rule group

Problem: Someone disabled the admission webhook, a PrometheusRule with a syntax error entered the cluster, and the Prometheus reload failed,so all new rules did not take effect (the old configuration kept running). Approach: Keep the webhook enabled; in CI, run promtool check rules (module 6); alert on PrometheusBadConfig (already in kps's default rules, based on prometheus_config_last_reload_successful).

Common errors and fixes

ServiceMonitor is created, but serviceMonitor/myapp/myapp/0 does not appear in /targets at all

Cause:①② mismatch: the label is not release: kps; or the Prometheus CR's serviceMonitorNamespaceSelector does not include that namespace; or the Operator judged a ServiceMonitor field invalid (for example, it references a Secret that does not exist).

kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus -o jsonpath='{.spec.serviceMonitorSelector}{" | "}{.spec.serviceMonitorNamespaceSelector}{"\n"}'
kubectl -n myapp get smon myapp --show-labels
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | grep -i -E 'myapp|skipping|invalid' | tail

Fix: add release: kps; if there are invalid objects, fix them based on the logs (commonly a basicAuth/tlsConfig reference to a Secret that does not exist).

/targets shows serviceMonitor/myapp/myapp/0 (0/0 up)

Cause:③④⑤ mismatch: namespaceSelector, Service labels or port name is wrong; or the Service has no ready endpoints at all.

kubectl -n myapp get svc --show-labels
kubectl -n myapp get svc myapp -o jsonpath='{.spec.ports[*].name}{"\n"}'
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp -o yaml | yq '.items[].endpoints[] | [.addresses[0], .conditions.ready]'
server returned HTTP status 404 Not Found (target DOWN)

Cause:path is wrong, or the port points to one that does not expose /metrics metrics (for example the Redis port rather than the redis-exporter port).

kubectl -n myapp port-forward svc/myapp 5000:5000 &  curl -si localhost:5000/metrics | head -3
Error from server (InternalError): … admission webhook "prometheusrulevalidate.monitoring.coreos.com" denied the request: Rules are not valid

Cause: PromQL syntax error (mismatched parentheses,by written in the wrong place, template field misspelled). After rejection by the webhook, the object does not enter the cluster.

yq '.spec' manifests/myapp/prometheusrule.yaml > /tmp/myapp.rules.yml
promtool check rules /tmp/myapp.rules.yml
Checking /tmp/myapp.rules.yml
  FAILED:
/tmp/myapp.rules.yml: 34:19: group "myapp.alerts", rule 3, "MyappHighErrorRate": could not parse expression: 1:58: parse error: unclosed left parenthesis
PrometheusRule has been created, but the Rules page has no myapp.alerts

Cause: Missing release: kps (ruleSelector); or the reload has not happened yet; or the reload failed.

kubectl -n monitoring logs prometheus-kps-kube-prometheus-stack-prometheus-0 -c config-reloader --tail=20
curl -s localhost:9090/api/v1/status/config >/dev/null && curl -s localhost:9090/metrics | grep prometheus_config_last_reload_successful
Command-line exercise
1. List all that will not be picked up by kps (ServiceMonitors missing the release=kps label).
kubectl get smon -A -l 'release!=kps'
2. Check which key of which rulefiles ConfigMap myapp-rules was written to.
kubectl -n monitoring get cm -l prometheus-name=kps-kube-prometheus-stack-prometheus -o json | jq -r '.items[] | .metadata.name as $n | .data | keys[] | select(startswith("myapp-")) | $n + " " + .'
Scenario analysis question
After upgrading myapp's Helm chart, all myapp curves in Grafana disappeared, but the Pods are normal,curl /metrics is normal, and Prometheus has no alerts. Give the troubleshooting order and explain how to make this kind of situation trigger an alert in the future.

Troubleshooting order: is serviceMonitor/myapp/… still present in /targets? If not → check whether the ServiceMonitor still exists and whether its labels still include release: kps (a chart upgrade may have changed labels or disabled the ServiceMonitor); if it exists but is 0/0 → compare the new Service's labels and port names (chart upgrades often change the port name from http to web). There are no alerts because up series simply disappear, so the up == 0 condition does not hold. Improvement: add an absent(up{job="myapp",namespace="myapp"}) alert (this module's MyappTargetMissing); in CI, check ServiceMonitor labels with kubeconform or policies.

Verified teaching videos

▶
Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step — Anton Putra
English · ServiceMonitor and PodMonitor hands-on
▶
Prometheus Monitoring - Steps to monitor third-party apps using Prometheus Exporter | Part 2 — TechWorld with Nana
English · connecting a third-party exporter with a ServiceMonitor, demonstrating the release label issue
▶
Prometheus Operator in Kubernetes Explained — That DevOps Guy
English · CRDs and selectors explained

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–20s
Scene: a chain of five links: Prometheus CR, ServiceMonitor, Service, port, Pod; each link shows the labels that must match.
Narration: whether a target appears depends on whether every link in this selection chain is connected.
Shot 2 · 20–50s
Scene: the ServiceMonitor's label reads release: prometheus; the Operator's gaze passes over it without stopping; the Targets page is empty, and the logs show no errors.
Narration: the most common failure is a label mismatch; it raises no error, it simply makes nothing happen.
Shot 3 · 50–80s
Scene: the label is changed to release: kps; the configuration Secret updates, config-reloader issues a reload, and the two Pods turn green one after another on the Targets page.
Narration: fix the label, the Operator generates the configuration, the reloader hot-loads it, and the target appears.
or score ≥ 70% in the “Quiz”

Module 3 · Managing the monitoring stack with Helm and GitOps

13:00 – 21:00 · The monitoring stack is itself an application: pin versions, keep values in Git, manage CRDs separately, Argo CD must use server-side apply, and releaseName determines the selector
8 minArgo CD v3.6.1 · Flux v2.10.0prometheus-operator-crds 33.0.2Helm never upgrades CRDs★★★★☆
Learning objectives
  • Design the monitoring-config repository: which component syncs the kps values, the CRDs and the monitoring declarations (ServiceMonitor / PrometheusRule / dashboard ConfigMaps), and in what order.
  • State the 4 ways to handle CRDs when upgrading kps and their trade-offs (manual server-side apply, a separate CRD chart,crds.upgradeJob, Flux crds: CreateReplace).
  • Write the Argo CD Application that manages kps (multi-source $values,ServerSideApply=true,releaseName: kps) and the key fields of the Flux HelmRelease.
Prerequisites: Installing Argo CD / Flux and the basics of Application and HelmRelease——this course does not repeat them, see Helm lesson 5(module 4 Argo CD managing Helm, module 5 Flux HelmRelease). Importance:★★★★☆

What: the three layers of “monitoring as code”

LayerContentsChange frequencyOwnerGitOps object
L0 CRD10 monitoring.coreos.com CRDsfollows the Operator versionPlatformSeparate Application / HelmRelease (synced first)
L1 monitoring stackkps chart + values (Prometheus resources, retention, Alertmanager configuration, Grafana settings)MonthlyPlatformApplication kps / HelmRelease kps
L2 monitoring declarationsServiceMonitor, PodMonitor, Probe, PrometheusRule, dashboard ConfigMapDailyApplication teamsAlongside the application in the app repo or app chart, or centralized in monitoring-config

Why: why the monitoring stack should use GitOps

  • Rebuildable: lesson 6 replicates the same stack on a second cluster; GitOps only has to point at the same repository.
  • Auditable: who changed retention from 15d to 2d and when, or who silenced Watchdog, is visible at a glance in the Git history.
  • Drift prevention: someone kubectl edit the Alertmanager configuration, and selfHeal will change it back.
  • Integration with CI: run promtool on the PR (module 6), the jsonnet build and terraform plan (module 5); merging publishes.

How: four special points of kps as a GitOps application

  1. CRDs are too large: crd-prometheuses.yaml about 840 KiB, which exceeds the client-side apply last-applied-configuration annotation limit of 262144 bytes, which produces metadata.annotations: Too long. The chart README explicitly requires Argo CD to use ServerSideApply=true.
  2. CRDs are not upgraded by helm upgrade: Helm only creates the CRDs on first install, from the crds/ directory. Each major kps version (for example 92.x → 93.x) usually comes with an Operator upgrade, and UPGRADE.md requires applying the kubectl apply --server-side new CRDs first. The four GitOps approaches are summarized in the table below.
  3. releaseName determines the selector: the template writes release: {{ .Release.Name }}. In Argo CD, helm.releaseName if not set, it equals the Application name; in Flux, releaseName if not set, it is [<targetNamespace>-]<HelmRelease name>. If the Application is named monitoring, the selector becomes release: monitoring, and all release: kps ServiceMonitors instantly “lose contact”, and every object name changes as well.
  4. Helm hooks: kps's admission webhook certificate is generated and patched by the pre/post-install hook Job. Flux runs the hooks unchanged via the Helm SDK; Argo CD maps them to PreSync/PostSync (run on every sync). If Argo CD shows the webhook configuration's caBundle keeps showing OutOfSync; for that field you can ignoreDifferences, or switch to prometheusOperator.admissionWebhooks.certManager.enabled=true.
CRD upgrade methodApproachProsNotes
A. Manual / CI stepsRun per UPGRADE.md before upgrading kubectl apply --server-side (the 10 CRD files under the Operator release tag)Matches official docsNot pure GitOps; easy to forget
B. Separate CRD chart (recommended in this lesson)prometheus-community/prometheus-operator-crds (33.0.2 = Operator v0.95.2; CRDs are in templates, so Helm upgrades them) as its own Application, sync-wave -1; kps sets crds.enabled: falseCRDs have their own version and audit trail; synced before kpsThe Operator versions of the two charts must match (kps appVersion = CRD chart appVersion)
C. crds.upgradeJob.enabled: truekps uses a hook Job to server-side apply the CRDs before upgradingSingle chartchart annotation marks it as preview feature, disabled by default; the Job needs RBAC and a pullable image
D. Flux install/upgrade.crds: CreateReplacehelm-controller handles the crds/ directorySimplest for Flux usersFlux only; Argo CD has no equivalent

When: Argo CD or Flux

Consistent with the Helm lesson 5 conclusion: if you need a UI and a centralized multi-cluster view, choose Argo CD (the release does not appear in helm list; Helm is only used for rendering); if you need native Helm semantics (hooks,helm history, automatic remediation on failure) choose Flux. A single kps can be managed by only one tool. This lesson's lab uses Argo CD; the “Command” page also gives the Flux version.

Common misconceptions① “Once it's under GitOps, there's no need to read UPGRADE.md”—manual steps for major versions (CRDs, field renames, default value changes) still need a human; tools like Renovate can open PRs automatically, but major versions must be reviewed manually. ② “The Application name can be anything”—it is the release name, and changing it changes every object name and the selector (unless you explicitly set releaseName). ③ “Syncing UI changes from Grafana dashboards back into Git is GitOps' job”—GitOps only goes Git → cluster; UI changes must either be prohibited (module 4's allowUiUpdates: false), or exported as JSON and submitted through a PR.

Repository to cluster: three Applications and sync order

Git: monitoring-config argocd/root.yaml (app-of-apps)argocd/crds.yaml wave -1argocd/kps.yaml wave 0argocd/config.yaml wave 1kps/values.yamlmanifests/myapp/*.yamlmanifests/blackbox/*.yamldashboards/*-cm.yaml App crds (wave -1)prometheus-operator-crds 33.0.2 App kps (wave 0)chart 93.3.0 + $values App monitoring-config (wave 1)path: manifests + dashboards 10 CRDs (ServerSideApply)must exist before any CR ns monitoring: Operator, Prometheus CR …releaseName: kps → selector release: kps ServiceMonitor / PrometheusRule / Probedashboard ConfigMap (grafana_dashboard: "1")
Figure 3-1 CRDs → monitoring stack → monitoring declarations, synced in order by sync wave; each layer can be rolled back independently

Upgrade flow: one kps major version upgrade

Renovate PR92.x → 93.3.0 Human reads UPGRADE.mdfield / default value changes CI: helm templatediff + promtool + kubeconform Bump CRD chart in the same PR33.0.2 (wave -1) Merge → syncWatch Watchdog / targets
Figure 3-2 PRs are opened automatically, major versions are reviewed by a human, CI validates, and CRDs and the chart are aligned in the same PR

Interactive: GitOps sync simulator

Choose a tool and scenario, and observe the controller's real behavior and errors. The logs imitate the status and event output of Argo CD / Flux.

Choose a scenario, then click “Sync”.
$ # log

Core commands

CommandPurposeNotes
helm template kps prometheus-community/kube-prometheus-stack --version 93.3.0 -n monitoring -f kps/values.yamlLocal renderingDiff against the old version's rendered output in the PR
argocd app diff kps / argocd app sync kpsView diff / syncCheck whether SSA takes effect on first sync
argocd app get kps --show-operationSync result and hook statusFailed resources and messages
flux reconcile hr kps -n monitoring --with-sourceReconcile immediatelyFlux version
flux get hr -n monitoringReady / messageFailure reason
kubectl get crd prometheuses.monitoring.coreos.com -o jsonpath='{.metadata.annotations.operator\.prometheus\.io/version}'Operator version of the CRDsCompare with kps appVersion

1. Argo CD: CRD Application (wave -1)

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: prometheus-operator-crds
  namespace: argocd
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
spec:
  project: default
  source:
    repoURL: https://prometheus-community.github.io/helm-charts
    chart: prometheus-operator-crds
    targetRevision: 33.0.2          # appVersion v0.95.2, aligned with kps 93.3.0
  destination:
    server: https://kubernetes.default.svc
    namespace: monitoring
  syncPolicy:
    automated: {prune: false, selfHeal: true}   # never auto-delete CRDs (deleting a CRD = deleting all CRs)
    syncOptions:
      - ServerSideApply=true
      - CreateNamespace=true

2. Argo CD: kps Application (multi-source + $values)

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: kps
  namespace: argocd
  annotations:
    argocd.argoproj.io/sync-wave: "0"
spec:
  project: default
  sources:
    - repoURL: https://prometheus-community.github.io/helm-charts
      chart: kube-prometheus-stack
      targetRevision: 93.3.0
      helm:
        releaseName: kps              # set explicitly: determines object names and the release: kps selector
        valueFiles:
          - $values/kps/values.yaml
        valuesObject:
          crds:
            enabled: false            # CRDs are managed by the Application above
    - repoURL: https://github.com/<GH_USER>/monitoring-config.git
      targetRevision: main
      ref: values
  destination:
    server: https://kubernetes.default.svc
    namespace: monitoring
  syncPolicy:
    automated: {prune: true, selfHeal: true}
    syncOptions:
      - ServerSideApply=true          # required by the chart README (CRDs and large objects)
      - CreateNamespace=true
  ignoreDifferences:                  # add only if the webhook caBundle keeps showing OutOfSync
    - group: admissionregistration.k8s.io
      kind: ValidatingWebhookConfiguration
      jqPathExpressions: ['.webhooks[]?.clientConfig.caBundle']
    - group: admissionregistration.k8s.io
      kind: MutatingWebhookConfiguration
      jqPathExpressions: ['.webhooks[]?.clientConfig.caBundle']

3. Argo CD: monitoring declarations Application (wave 1)

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: monitoring-config
  namespace: argocd
  annotations:
    argocd.argoproj.io/sync-wave: "1"
spec:
  project: default
  source:
    repoURL: https://github.com/<GH_USER>/monitoring-config.git
    targetRevision: main
    path: manifests
    directory: {recurse: true}
  destination:
    server: https://kubernetes.default.svc
  syncPolicy:
    automated: {prune: true, selfHeal: true}
    syncOptions:
      - ServerSideApply=true
      - SkipDryRunOnMissingResource=true   # CRDs may not be ready yet during first bootstrap
kubectl apply -n argocd -f argocd/crds.yaml -f argocd/kps.yaml -f argocd/config.yaml
argocd app list
argocd app get kps
NAME                             SYNC STATUS   HEALTH STATUS
argocd/monitoring-config         Synced        Healthy
argocd/kps                       Synced        Healthy
argocd/prometheus-operator-crds  Synced        Healthy

sync waves only take effect within the same sync operation (for example, the parent Application of app-of-apps); when three independent Applications are created at once, Argo CD syncs each on its own, and then you rely on retries and SkipDryRunOnMissingResource. In production, wrap them in one parent Application (app-of-apps) so the waves take full effect.

4. Flux equivalent configuration

apiVersion: source.toolkit.fluxcd.io/v1
kind: HelmRepository
metadata:
  name: prometheus-community
  namespace: monitoring
spec:
  interval: 1h
  url: https://prometheus-community.github.io/helm-charts
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: kps
  namespace: monitoring
spec:
  interval: 30m
  releaseName: kps
  chart:
    spec:
      chart: kube-prometheus-stack
      version: "93.3.0"
      sourceRef: {kind: HelmRepository, name: prometheus-community}
  install:
    crds: CreateReplace           # Flux creates and replaces the CRDs in the chart's crds/ directory
  upgrade:
    crds: CreateReplace
    remediation: {retries: 2}
  valuesFrom:
    - kind: ConfigMap
      name: kps-values            # generated from kps/values.yaml by the Kustomization's configMapGenerator
      valuesKey: values.yaml
flux reconcile hr kps -n monitoring --with-source
flux get hr -n monitoring
helm list -n monitoring          # Flux uses the Helm SDK, so the release is visible
NAME  REVISION  SUSPENDED  READY  MESSAGE
kps   93.3.0    False      True   Helm upgrade succeeded for release monitoring/kps.v2 with chart kube-prometheus-stack@93.3.0
NAME  NAMESPACE   REVISION  STATUS    CHART                          APP VERSION
kps   monitoring  2         deployed  kube-prometheus-stack-93.3.0   v0.95.2

5. Migrating from a manual helm install to Argo CD

# Module 1 installed kps with helm. When Argo CD takes over, object names stay the same (releaseName: kps), so no reinstall is needed:
argocd app diff kps            # should show only label/annotation differences
argocd app sync kps
# After takeover, the old release record is still in helm list; once Argo CD is healthy, delete the Secret that stores the Helm release (this does not affect resources):
kubectl -n monitoring delete secret -l owner=helm,name=kps

Risk: Running it after the last step helm uninstall kps will fail (release not found), which is exactly the goal: from then on only Argo CD can change it. If the CRDs were originally created by kps's helm release,crds.enabled: false removing the release record will not delete them (Helm never deletes CRDs), and the CRD Application's first sync takes over field ownership via server-side apply.

Goal: have Argo CD take over the kps installed by hand in module 1 and the ServiceMonitor / PrometheusRule from module 2, and verify the roles of selfHeal and releaseName. Environment: the kind lab has Argo CD installed (Helm lesson 5, or kubectl create ns argocd && kubectl apply -n argocd --server-side -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.1/manifests/install.yaml); the GitHub repository monitoring-config is pushed.
Push the repository:
cd ~/promlab/monitoring-config
git add . && git commit -m "chore: kps values, myapp monitoring" && gh repo create monitoring-config --public --source . --push
Create three Applications: following steps 1–3 of the “Command” page, replace <GH_USER> then apply, and wait until everything is Synced / Healthy.
Verify selfHeal: manually delete myapp's PrometheusRule and watch Argo CD recreate it within seconds.
kubectl -n myapp delete prometheusrule myapp-rules
sleep 15; kubectl -n myapp get prometheusrule
prometheusrule.monitoring.coreos.com "myapp-rules" deleted
NAME          AGE
myapp-rules   9s
Change configuration through Git: change the kps/values.yaml of retention: 2d to 3d and push; argocd app sync kps after syncing, confirm that kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.retention}' is 3d; the Prometheus Pod performs a rolling restart.
(Thought experiment, do not run in a shared environment) releaseName pitfall: if you delete helm.releaseName and rename the Application to monitoring,argocd app diff it will show: all object names change from kps-… to monitoring-kube-prometheus-stack-…, and the Prometheus CR's selector becomes release: monitoring. Module 2's MyappTargetMissing will fire after 5 minutes.
Cleanup: keep it (lessons 6 and 7 continue to use it). To remove GitOps while keeping resources, first argocd app set kps --sync-policy none, then delete the Application with its finalizer removed (non-cascading delete).

Case 1: all ServiceMonitors stop working after an upgrade

Problem: A team renamed the Argo CD Application from kube-prometheus-stack to monitoring-prod (to unify naming). After sync, the Prometheus CR was recreated under a new name and its selector became release: monitoring-prod, all business ServiceMonitors lost contact, and the data in the old PVC was no longer mounted. Approach: Roll back the Application name or explicitly set helm.releaseName; long term, set in values prometheus.prometheusSpec.serviceMonitorSelector.matchLabels to a fixed, release-independent label (for example monitoring.example.com/scrape: "true"), and use fullnameOverride fixed object names. Limitation: Changing the selector requires notifying all teams to update their ServiceMonitor labels in sync.

Case 2: Renovate auto-merged a major version

Problem: The auto-merged kps major upgrade introduced new CRD fields; the new Operator version failed because the CRDs were outdated, with errors such as failed to list *v1.ScrapeConfig and similar errors, and Prometheus configuration stopped updating. Approach: Renovate rule: group kps and prometheus-operator-crds together (same PR), and disable automerge for major versions; CI renders both charts and checks that their appVersion values match.

Case 3: multiple clusters

Problem: 20 clusters, each with its own copy of values; the differences are hard to manage. Approach: Argo CD ApplicationSet (cluster generator) + layered values: kps/values.yaml (common) + kps/clusters/<name>.yaml (externalLabels cluster, retention, remote_write address). Lesson 6 uses externalLabels and remote_write to aggregate multiple clusters into Thanos / Mimir.

Common errors and fixes

CustomResourceDefinition.apiextensions.k8s.io "prometheuses.monitoring.coreos.com" is invalid: metadata.annotations: Too long: must have at most 262144 bytes

Cause: client-side apply wrote the entire object into last-applied-configuration an annotation.

Fix: In Argo CD, add syncOptions: [ServerSideApply=true]; for manual operations, use kubectl apply --server-side.

The Kubernetes API could not find monitoring.coreos.com/ServiceMonitor for requested resource myapp/myapp. Make sure the "ServiceMonitor" CRD is installed on the destination cluster.

Cause: monitoring declarations synced before the CRDs (first bootstrap, or the CRD Application failed).

argocd app get prometheus-operator-crds
kubectl get crd servicemonitors.monitoring.coreos.com

Fix: sync waves + app-of-apps; SkipDryRunOnMissingResource=true fix the CRD Application, then re-sync.

Operator log: … the server could not find the requested resource (get prometheusagents.monitoring.coreos.com) / new field rejected by strict decoding

Cause: The Operator was upgraded, but the CRDs are still the old version (Helm does not upgrade CRDs).

kubectl get crd prometheuses.monitoring.coreos.com -o jsonpath='{.metadata.annotations.operator\.prometheus\.io/version}{"\n"}'
kubectl -n monitoring get deploy kps-kube-prometheus-stack-operator -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'

Fix: Upgrade the CRDs per UPGRADE.md using server-side apply, or upgrade the CRD chart so its appVersion matches kps.

Flux: HelmRelease kps: install retries exhausted / context deadline exceeded

Cause: kps has many components, and the default 5-minute timeout is not enough (slow image pulls); or the webhook hook Job failed.

flux get hr kps -n monitoring
kubectl -n monitoring get jobs; kubectl -n monitoring get events --sort-by=.lastTimestamp | tail

Fix:spec.timeout: 15m; fix image pulls; then flux reconcile hr kps -n monitoring --reset reset the failure count (see Helm lesson 5).

In Argo CD, kps keeps showing OutOfSync (caBundle / data of some Secrets)

Cause: the hook Job patched the webhook's caBundle, which differs from the rendered result.

Fix: for these fields, configure ignoreDifferences (see step 2 of the “Command” page), or enable the cert-manager approach, or in the lab prometheusOperator.admissionWebhooks.enabled=false disable the webhook (this loses rule syntax validation; not recommended for production).

Command-line exercise
1. In a PR, compare the rendered differences between kps 93.2.2 and 93.3.0 using the same values.
for v in 93.2.2 93.3.0; do helm template kps prometheus-community/kube-prometheus-stack --version $v -n monitoring -f kps/values.yaml --skip-crds > /tmp/kps-$v.yaml; done
diff -u /tmp/kps-93.2.2.yaml /tmp/kps-93.3.0.yaml | head -50

When the helm-diff plugin is available, you can also use helm diff upgrade on the live release (Flux scenario).

2. Check whether the CRD chart and kps Operator versions match.
helm show chart prometheus-community/kube-prometheus-stack --version 93.3.0 | yq .appVersion
helm show chart prometheus-community/prometheus-operator-crds --version 33.0.2 | yq .appVersion
Scenario analysis question
The company decides to migrate the monitoring stack of three clusters from “separate helm install” to Argo CD, without losing data or creating an alerting gap during the migration. Give the steps.

① Export each cluster's current values (helm get values kps -n monitoring) and organize them in Git, pinning the current chart version (do not upgrade during the migration). ② First create the CRD Application (ServerSideApply, prune: false) and confirm there is no difference from the existing CRDs. ③ Create the kps Application, with releaseName a releaseName identical to the original release; first turn off automated,argocd app diff only label/annotation differences should appear; sync manually. Object names unchanged → StatefulSet and PVC stay in place, so no data is lost. ④ After verifying that Watchdog alerts keep arriving and the number of targets is unchanged, enable automated + selfHeal and delete the Helm release Secret. ⑤ Migrate one cluster at a time, starting with a non-production one.

Verified teaching videos

▶
What is GitOps, How GitOps works and Why it's so useful — TechWorld with Nana
English · GitOps concepts review
▶
ArgoCD Tutorial for Beginners | GitOps CD for Kubernetes — TechWorld with Nana
English · Argo CD Application basics (recorded before v3)
▶
Flux CD v2 With GitOps Toolkit - Kubernetes Deployment And Sync Mechanism — DevOps & AI Toolkit
English · Flux sync mechanism

No verified dedicated video was found for “managing kube-prometheus-stack and its CRD upgrades with GitOps”; see the storyboard script below.

Official documentation

Video storyboard script (about 80 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–25s
Scene: in the Git repository, three folders light up (CRD, kps, manifests), labelled waves -1, 0 and 1 in turn, with arrows pointing at the cluster.
Narration: the monitoring stack is handed to GitOps in three layers: first the CRDs, then the monitoring stack, and finally each team's monitoring declarations.
Shot 2 · 25–55s
Scene: a huge CRD file hits a “262144 bytes” wall, then passes smoothly after switching to ServerSideApply.
Narration: kps's CRDs are too large, so Argo CD must enable server-side apply; and Helm does not upgrade CRDs, so they must be managed separately.
Shot 3 · 55–80s
Scene: the Application name changes from kps to monitoring, and the release: kps label on all ServiceMonitors greys out and disconnects.
Narration: the release name is the selector; pin the releaseName before renaming.
or score ≥ 70% in the “Quiz”

Module 4 · Grafana provisioning: data sources, dashboards and alerts as code

21:00 – 28:00 · Grafana reads the provisioning directory at startup; in Kubernetes, kiwigrid k8s-sidecar writes labelled ConfigMaps into these directories, so “committing one ConfigMap = publishing one dashboard”
7 minGrafana 13.3.1 · grafana chart 14.4.1k8s-sidecar 2.14.3Alerting sidecar disabled by default★★★★☆
Learning objectives
  • Distinguish Grafana's three “as code” entry points: file provisioning (data sources, dashboard providers, alerting resources, plugins),HTTP API (used by tools such as Terraform, module 5),UI (for exploration only).
  • Understand how the kps sidecar works: the label grafana_dashboard: "1" / grafana_datasource: "1",searchNamespace: ALL, folder annotation, and hot reloading.
  • Publish the RED dashboard ConfigMap for myapp, fixing the uid and data source uid: prometheus; define contact points and notification policies with provisioning.
Prerequisites: The Grafana provisioning directory from lesson 1 (Docker Compose version) and the RED dashboard; modules 1–3. Importance:★★★★☆

What: what provisioning is

Grafana reads the YAML under provisioning/ at startup (and when the Admin API reload endpoint is called): datasources/,dashboards/ (defines “dashboard providers” pointing to a directory holding JSON files),alerting/ (alert rule groups, contact points, notification policies, templates, mute timings),plugins/. In lesson 1 you used ~/promlab/grafana/provisioning the first two in it.

ResourceDocker Compose (lesson 1)How kps does itDefault
Data sourcesprovisioning/datasources/prometheus.yamlkps automatically creates the data source ConfigMap (uid: prometheus,uid: alertmanager), loaded by the sidecar; extra data sources use grafana.additionalDataSources or grafana_datasource: "1" a ConfigMap/Secret withenabled
Dashboardsprovider YAML + JSON directorywith grafana_dashboard: "1" a ConfigMap; the sidecar writes it to /tmp/dashboards, and the chart's built-in provider reads from itenabled,searchNamespace: ALL
Alerting resourcesprovisioning/alerting/*.yamlgrafana.sidecar.alerts.enabled: true after, with grafana_alert labelled ConfigMaps are loadeddisabled
Grafana settingsgrafana.ini / environment variablesgrafana."grafana.ini" values—

Why: why dashboards should be in Git

  • Rebuild means consistent: Grafana Pods have no persistent volume by default (kps default); after a restart, all changes made in the UI are lost, whereas provisioned dashboards are restored automatically every time.
  • Review: PromQL changes go through PRs like code, avoiding “someone broke the production dashboard”.
  • Multiple environments / multiple clusters: the same JSON appears in every cluster's Grafana; the uid is fixed, so links (for example, the dashboard URL in an alert) do not change.

How: the sidecar mechanism

  1. In the Grafana Pod, the grafana-sc-dashboard container (kiwigrid/k8s-sidecar) uses the Kubernetes API to watch watch all namespaces (kps sets searchNamespace: ALL, so the chart creates a ClusterRole), for objects carrying the grafana_dashboard=1 label: ConfigMaps / Secrets.
  2. each data key is written as a file into the shared emptyDir /tmp/dashboards; if folderAnnotation: grafana_folder is set, it writes to /tmp/dashboards/<annotation value>/.
  3. Grafana's built-in sidecar dashboard provider (foldersFromFilesStructure: true when enabled, creates folders per subdirectory) periodically scans the directories, writing new/changed JSON into the Grafana database; when a ConfigMap is deleted, its files are removed and the dashboard goes with it.
  4. the data source sidecar writes /etc/grafana/provisioning/datasources and then calls POST /api/admin/provisioning/datasources/reload, no restart needed.

Key constraints:① the dashboard JSON's uid must be globally unique and fixed, otherwise two ConfigMaps overwrite each other; ② in panels, the datasource.uid must be written as prometheus (kps's default data source uid), not the random uid carried over from export; ③ ConfigMap size limit 1 MiB; ④ provisioned dashboards can be edited in the UI, but saving will be rejected (allowUiUpdates: false, kps default), so changes must be exported as JSON and submitted via PR; ⑤ alerting resources from file provisioning cannot be edited in the UI.

When: choose provisioning or API (Terraform)

NeedRecommendationReason
Dashboards shipped with the application (the app chart includes a ConfigMap)sidecar ConfigMapSame lifecycle as ServiceMonitor; GitOps syncs automatically
Grafana outside the cluster (Azure Managed Grafana, AMG, Grafana Cloud)Terraform provider (module 5)Managed Grafana cannot mount ConfigMaps
Teams, permissions, service accounts, folder permissionsTerraformprovisioning does not cover RBAC resources
Alert rulesPrefer Prometheus rules (PrometheusRule, module 2); for Grafana-managed alerts use provisioning or TerraformPrometheus rules can be tested with promtool and do not depend on Grafana being available
Two-way dashboard sync with Git; edit in the UI and then open a PRGrafana Git Sync (see Grafana “as code” docs; feature status per official documentation)Not covered in this lesson
Common misconceptions① “Writing the label as grafana_dashboard: "true" is also fine”—kps sets labelValue: "1", the value must be the string "1". ② “A ConfigMap is only discovered if it is in the monitoring namespace”—kps's default searchNamespace: ALL, so placing it in the myapp namespace also works (recommended alongside the application). ③ “Exported JSON can be used as-is”—the UI's “Export for sharing externally” changes the data source to ${DS_PROMETHEUS} an input variable that the sidecar does not replace; instead export plain JSON and change the data source uid to prometheus (or use a template variable ${datasource}). ④ “The alerting sidecar is enabled by default”—in the grafana chart, sidecar.alerts.enabled defaults to false.

Architecture diagram: inside the Grafana Pod

Any namespace CM myapp-red-dashboardgrafana_dashboard: "1" CM kps-…-grafana-datasourcegrafana_datasource: "1" CM myapp-alertinggrafana_alert: "1" (must be enabled) Pod kps-grafana (3/3) grafana-sc-dashboardwatch ConfigMap/Secret grafana-sc-datasourceswrite files + reload API /tmp/dashboardsmyapp/myapp-red.json provisioning/datasources/*.yaml grafanadashboard provider scanswrites to grafana.db:3000 sidecar uses ServiceAccount + ClusterRole (list/watch configmaps, secrets)emptyDir shared volume: after a Pod restart, the sidecar rewrites it
Figure 4-1 ConfigMap → sidecar → shared volume → Grafana provider → database

Decision diagram: where a dashboard comes from

Explore in UIExplore / drafts Export JSON / write Jsonnetfixed uid · ds uid PR + CIjsonnet build · lint In-cluster Grafana: ConfigMap + sidecarGitOps sync (this module) Managed/external Grafana: Terraformgrafana_dashboard resource (module 5)
Figure 4-2 The UI is for exploration only; “publishing” always starts from Git

Animation: the sidecar loads a dashboard ConfigMap

Choose a ConfigMap form, play, and observe the sidecar's and Grafana's reactions (the logs imitate the k8s-sidecar and Grafana log formats).

Choose, then click “Play”.
$ # log

Core commands

CommandPurposeNotes
kubectl get cm -A -l grafana_dashboard=1List all dashboards that will be loadedkps ships with dozens
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20sidecar logsCheck whether files were written
kubectl -n monitoring exec deploy/kps-grafana -c grafana -- ls -R /tmp/dashboardsCheck the shared volume contentsCheck whether the folder annotation takes effect
curl -s -u admin:$PW 'localhost:3000/api/search?query=myapp'Grafana API searchConfirm uid and folder
curl -s -u admin:$PW localhost:3000/api/dashboards/uid/myapp-red | jq .meta.provisionedWhether it is provisionedtrue means the UI cannot save
curl -X POST -u admin:$PW localhost:3000/api/admin/provisioning/dashboards/reloadRescan immediatelyalerting / datasources also have corresponding reload endpoints

1. myapp RED dashboard JSON (fixed uid and data source uid)

{
  "uid": "myapp-red",
  "title": "myapp / RED",
  "tags": ["myapp", "red", "provisioned"],
  "timezone": "browser",
  "schemaVersion": 41,
  "refresh": "30s",
  "time": {"from": "now-1h", "to": "now"},
  "templating": {"list": [
    {"name": "namespace", "type": "query", "datasource": {"type": "prometheus", "uid": "prometheus"},
     "query": "label_values(myapp_http_requests_total, namespace)", "refresh": 2, "current": {"text": "myapp", "value": "myapp"}}
  ]},
  "panels": [
    {"id": 1, "type": "timeseries", "title": "Request rate (RPS)", "gridPos": {"x": 0, "y": 0, "w": 12, "h": 8},
     "datasource": {"type": "prometheus", "uid": "prometheus"},
     "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
     "targets": [{"refId": "A", "expr": "sum by (route) (rate(myapp_http_requests_total{namespace=\"$namespace\"}[$__rate_interval]))", "legendFormat": "{{route}}"}]},
    {"id": 2, "type": "timeseries", "title": "Error rate (5xx ratio)", "gridPos": {"x": 12, "y": 0, "w": 12, "h": 8},
     "datasource": {"type": "prometheus", "uid": "prometheus"},
     "fieldConfig": {"defaults": {"unit": "percentunit", "max": 1}, "overrides": []},
     "targets": [{"refId": "A", "expr": "sum(rate(myapp_http_requests_total{namespace=\"$namespace\",status=~\"5..\"}[$__rate_interval])) / sum(rate(myapp_http_requests_total{namespace=\"$namespace\"}[$__rate_interval]))", "legendFormat": "5xx ratio"}]},
    {"id": 3, "type": "timeseries", "title": "Latency P50 / P95 / P99", "gridPos": {"x": 0, "y": 8, "w": 24, "h": 8},
     "datasource": {"type": "prometheus", "uid": "prometheus"},
     "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
     "targets": [
       {"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{namespace=\"$namespace\"}[$__rate_interval])))", "legendFormat": "p50"},
       {"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{namespace=\"$namespace\"}[$__rate_interval])))", "legendFormat": "p95"},
       {"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(myapp_http_request_duration_seconds_bucket{namespace=\"$namespace\"}[$__rate_interval])))", "legendFormat": "p99"}]}
  ]
}

schemaVersion Use a recent schemaVersion value; Grafana migrates older schemas automatically on load. Module 5 generates the same JSON with Grafonnet, so you don't have to write it by hand.

2. Generate the ConfigMap (label + folder annotation)

cd ~/promlab/monitoring-config
kubectl create configmap myapp-red-dashboard -n myapp \
  --from-file=myapp-red.json=dashboards/myapp-red.json \
  --dry-run=client -o yaml \
| yq '.metadata.labels.grafana_dashboard = "1" | .metadata.annotations.grafana_folder = "myapp"' \
> manifests/myapp/dashboard-cm.yaml
kubectl apply --server-side -f manifests/myapp/dashboard-cm.yaml
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=5
configmap/myapp-red-dashboard serverside-applied
{"time": "2026-11-15T10:21:07Z", "level": "INFO", "msg": "Writing /tmp/dashboards/myapp/myapp-red.json (ascii)"}
PW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
curl -s -u admin:$PW 'localhost:3000/api/search?query=myapp' | jq -r '.[] | [.uid,.title,.folderTitle] | @tsv'
myapp-red	myapp / RED	myapp

3. Enable the alerting sidecar and provision contact points and notification policies (values snippet)

grafana:
  sidecar:
    alerts:
      enabled: true
      label: grafana_alert
      labelValue: "1"
      searchNamespace: ALL
apiVersion: v1
kind: ConfigMap
metadata:
  name: myapp-grafana-alerting
  namespace: monitoring
  labels:
    grafana_alert: "1"
data:
  myapp-alerting.yaml: |
    apiVersion: 1
    contactPoints:
      - orgId: 1
        name: myapp-webhook
        receivers:
          - uid: myapp-webhook
            type: webhook
            settings:
              url: http://alert-sink.monitoring.svc:8080/hook   # fake receiver for the lab; in production, inject via Secret
    policies:
      - orgId: 1
        receiver: myapp-webhook
        group_by: ['grafana_folder', 'alertname']
    groups:
      - orgId: 1
        name: myapp-grafana
        folder: myapp
        interval: 1m
        rules:
          - uid: myapp-redis-down-g
            title: MyappRedisDown (Grafana-managed)
            condition: C
            data:
              - refId: A
                relativeTimeRange: {from: 300, to: 0}
                datasourceUid: prometheus
                model: {refId: A, expr: 'min(myapp_redis_up{namespace="myapp"})', instant: true}
              - refId: C
                datasourceUid: __expr__
                model:
                  refId: C
                  type: threshold
                  expression: A
                  conditions:
                    - evaluator: {type: lt, params: [1]}
            for: 1m
            noDataState: NoData
            execErrState: Error
            labels: {severity: critical}
            annotations: {summary: "myapp cannot connect to Redis"}

Note: This lesson recommends PrometheusRule as the primary alerting mechanism (unit-testable; Grafana downtime does not stop alerts). The Grafana-managed rules here only demonstrate the provisioning format; in production choose one of the two, to avoid sending the same alert twice. policies This replaces the entire notification policy tree; an org can be defined in only one place.

4. Extra data source (for example, Thanos Query from lesson 6)

grafana:
  additionalDataSources:
    - name: Thanos
      uid: thanos
      type: prometheus
      url: http://thanos-query.monitoring.svc:9090
      access: proxy
      isDefault: false
Goal: publish the myapp RED dashboard (folder myapp), confirm its provisioned status, and modify it through Git. Environment: modules 1–3; Grafana port-forwarded to 3000.
Write the JSON and generate the ConfigMap: follow steps 1 and 2 of the “Command” page; place it in manifests/myapp/, commit and push, and let Argo CD (the monitoring-config application) sync it instead of applying by hand.
git add dashboards manifests/myapp/dashboard-cm.yaml && git commit -m "feat: myapp RED dashboard" && git push
argocd app sync monitoring-config
Generate traffic:
kubectl -n myapp port-forward svc/myapp 5000:5000 &
for i in $(seq 1 300); do curl -s localhost:5000/ >/dev/null; curl -s localhost:5000/nope >/dev/null; sleep 0.2; done
Open Grafana → Dashboards → myapp → “myapp / RED”; all three panels should have data.
Verify provisioned status: in the UI, change a panel title and click Save; confirm the “Cannot save provisioned dashboard” message appears. Check via the API:
curl -s -u admin:$PW localhost:3000/api/dashboards/uid/myapp-red | jq '.meta | {provisioned, provisionedExternalId, folderTitle}'
{
  "provisioned": true,
  "provisionedExternalId": "myapp/myapp-red.json",
  "folderTitle": "myapp"
}
Change through Git: change the P95 panel to also show P99.9 (add one target), commit and sync; the UI updates within about 1 minute — at no point was anything saved in the UI.
(Optional) alerting provisioning: enable the alerting sidecar per step 3 of the “Command” page (edit values → Argo CD syncs kps; the Grafana Pod is rebuilt and becomes 4/4), commit the ConfigMap, and confirm that myapp-webhook appears under Alerting → Contact points and shows “Provisioned”.
Cleanup: keep the dashboard; if you did the optional step and don't need Grafana-managed alerts, delete the ConfigMap from Git and change sidecar.alerts.enabled back to false.

Case 1: dashboards shipped with the application chart

Problem: The platform team maintains hundreds of dashboards and cannot keep up with application changes. Approach: Add a dashboard file to the application chart templates/dashboard-cm.yaml, using .Files.Get "dashboards/red.json" to generate grafana_dashboard: "1" a ConfigMap with the matching label; the dashboard and metrics code change in the same PR. Limitations: Template braces in the JSON {{ }} (legendFormat) conflict with Helm templates; use .Files.Get to read the file as-is rather than putting it into the template, or write {{`{{route}}`}}.

Case 2: all self-built dashboards “disappear” after Grafana restarts

Problem: kps's default Grafana has no persistent volume; dashboards created in the UI by the operations team all disappeared after node maintenance. Approach: Short term, enable grafana.persistence.enabled; long term, mandate “UI is for exploration only”, make all dashboards provisioned, and back up the database (or use an external MySQL/PostgreSQL).

Case 3: uid conflicts make dashboards “change at random”

Problem: Two teams copied the same community dashboard JSON with the same uid; the sidecar load order decided which one overwrote the other, and Grafana logs repeatedly showed “the same UID is used more than once”. Approach: In CI, check that every dashboard JSON's uid is unique (jq -r .uid dashboards/*.json | sort | uniq -d), and adopt a uid naming convention of <team>-<service>-<topic>.

Common errors and fixes

ConfigMap created, but no dashboard in Grafana and no “Writing …” in the sidecar logs

Cause: Wrong label key or value (grafana_dashboard: "true"); searchNamespace was changed to monitoring; sidecar RBAC is missing.

kubectl get cm -A -l grafana_dashboard=1 | grep myapp
helm get values kps -n monitoring -a | yq '.grafana.sidecar.dashboards | {label, labelValue, searchNamespace}'
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard | grep -i -E 'error|forbidden' | tail
logger=provisioning.dashboard … msg="failed to load dashboard from " file=/tmp/dashboards/myapp/myapp-red.json error="invalid character '}' looking for beginning of object key string"

Cause: JSON syntax error (extra comma). The sidecar still writes the file; Grafana is what fails to load it.

jq empty dashboards/myapp-red.json && echo OK
kubectl -n monitoring logs deploy/kps-grafana -c grafana | grep -i 'provisioning.dashboard' | tail

Prevention: In CI, run jq empty on all JSON; generate with Grafonnet (module 5).

Panel shows Datasource ${DS_PROMETHEUS} was not found

Cause: The JSON exported with “Export for sharing externally” contains __inputs, and provisioning does not substitute it.

Fix: Change all "uid": "${DS_PROMETHEUS}" to "uid": "prometheus", and remove __inputs; or define a data source template variable in the dashboard datasource (type: datasource, query: prometheus), and have panels use ${datasource}.

Cannot save provisioned dashboard / Dashboard cannot be deleted because it was provisioned

Cause: Expected behavior (allowUiUpdates: false,disableDeletion).

Approach: After editing in the UI, use “Export → Export as JSON” (leave “externally” unchecked), replace the JSON in the repository and open a PR; or delete the ConfigMap in Git to remove the dashboard.

Grafana log: the same UID is used more than once / dashboard with the same uid already exists in another folder

Cause: Two JSON files have the same uid.

kubectl -n monitoring exec deploy/kps-grafana -c grafana -- sh -c 'grep -rho "\"uid\": *\"[^\"]*\"" /tmp/dashboards | sort | uniq -d'
Command-line exercise
1. Replace the data source uid in all dashboard JSON files in the repository with prometheus, and check that uids are unique.
for f in dashboards/*.json; do jq '(.. | objects | select(has("datasource") and (.datasource|type)=="object") | .datasource.uid) |= "prometheus"' "$f" > "$f.tmp" && mv "$f.tmp" "$f"; done
jq -r .uid dashboards/*.json | sort | uniq -d

No output from the second command means the uids are unique. Note: template variables' datasource is replaced too, which is what you want; mixed-data-source dashboards need more careful filtering.

2. Make Grafana rescan the dashboard directory immediately (without restarting).
curl -s -X POST -u admin:$PW localhost:3000/api/admin/provisioning/dashboards/reload
Scenario analysis question
The business team wants to “drag and drop dashboards in the Grafana UI and have changes go into Git automatically”, while the platform team requires that “dashboards must go through PR review”. How would you design a workflow that satisfies both?

Option 1 (fewest tools): edit in the UI → Export JSON → paste into the repository and open a PR (a script can be provided curl /api/dashboards/uid/X | jq .dashboard > dashboards/X.json) → CI validates JSON and uid → after merge, the sidecar loads it. Option 2: use Grafana's Git Sync (saving in the UI creates a branch/PR; feature status and supported Git providers per official documentation). Option 3: write dashboards with Grafonnet / Foundation SDK, and use the UI only for prototyping. Either way: provisioned dashboards must block UI saves, so the “UI version” and the “Git version” cannot diverge.

Verified teaching videos

▶
Grafana 12 TL;DR: Observability as Code, Dynamic Dashboards & More Explained in 7 Min | Grafana Labs — Grafana
English · Grafana 12's “observability as code” direction (Git Sync, new schema); this lesson is based on 13.3.1
▶
Git Sync: Observability as code built for scale | Demo | Grafana Labs — Grafana
English · Git Sync demo (not covered in this lesson; extension material)
▶
Grafana dashboards as code demo — Sebastian Thomas
English · community demo

No verified dedicated video was found for “kps sidecar loads dashboard ConfigMap”; see the storyboard script below.

Official documentation

Video storyboard script (about 70 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–20s
Scene: Grafana restarts, and dashboards created by hand in the UI disappear; beside it, the JSON files in the Git repository glow.
Narration: changes made in the UI are lost; dashboards in Git are not.
Shot 2 · 20–50s
Scene: a ConfigMap labelled grafana_dashboard = 1 is picked up by the sidecar and written to the shared directory; after the Grafana provider scans it, the dashboard appears in the myapp folder.
Narration: the sidecar watches labelled ConfigMaps, writes them out as files, and Grafana loads them periodically.
Shot 3 · 50–70s
Scene: a user clicks Save in the UI, a “cannot save provisioned dashboard” message appears, and the view switches to a Git PR.
Narration: changes go through a PR; this is dashboards as code.
or score ≥ 70% in the “Quiz”

Module 5 · Terraform Grafana provider and Grafonnet

28:00 – 35:00 · Grafonnet (Jsonnet) writes dashboards as reusable functions; Terraform manages folders, dashboards, contact points, notification policies and rule groups through the Grafana HTTP API — applicable to any Grafana that exposes the API, including managed Grafana
7 mingrafana/grafana provider v4.55.0Terraform 1.17.xGrafonnet: experimental · not officially supported★★★★☆
Learning objectives
  • Configure the provider with a service account token, and manage grafana_folder,grafana_dashboard,grafana_contact_point,grafana_notification_policy, and grafana_rule_group.
  • Understand the provenance (not editable in the UI, with the exception of disable_provenance ) and drift detection for dashboards.
  • Use Grafonnet to generate the myapp overview dashboard: jb install → jsonnet -J vendor → Terraform file() read it; know that Grafana officially prefers the Foundation SDK.
Prerequisites: Terraform basics (init/plan/apply, variables, state) — for systematic study see Terraform 8 hours; module 4. Importance:★★★★☆

What: two tools, each handling one part

ToolInputOutputProblem solved
GrafonnetJsonnet code (functions, variables, loops)dashboard JSONHand-written JSON is verbose, copy-pasted and hard to reuse (e.g. RED panels for 20 services)
Foundation SDKGo / TypeScript / Python / Java / PHP codedashboard JSON (and other resources)Same as above; the alternative Grafana recommends (Grafana docs note Grafonnet is not officially supported)
Terraform grafana providerHCL + JSONReal resources in Grafana (via HTTP API)Deployment, state, drift detection; covers resources that provisioning cannot manage (service accounts, teams, permissions, folders, Grafana Cloud)

Typical pipeline: grafonnet/*.jsonnet → (CI build) → dashboards/build/*.json → Terraform grafana_dashboard.config_json = file(...) → Grafana. An in-cluster Grafana can also put the same JSON into a ConfigMap (module 4).

Why: when Terraform is needed

  • Grafana is not in the cluster: Azure Managed Grafana, Amazon Managed Grafana (lessons 3 and 4), Grafana Cloud — no ConfigMap can be mounted, so only the API works.
  • Resource types: service accounts, teams, folder permissions, data sources (including secrets), contact points, notification policies, mute timings, SLOs (Grafana Cloud) … The provider covers more resource types than any other Grafana “as code” approach.
  • Same repository as infrastructure: Terraform code that creates the AMG workspace is managed together with the dashboards and data sources inside it.

How: key provider behaviors

  1. Authentication: auth Supports a service account token (recommended,glsa_…) or "user:password" (experimental only). The token's permissions determine which resources can be managed; managed Grafana issues tokens through its own identity mechanism.
  2. Dashboards: config_json is the full JSON; the uid comes from the JSON itself. The provider normalizes the JSON on read (removing id, version, etc.), so after someone edits and saves in the UI, the next plan will show a config_json diff → drift is detected and reverted at apply time. Dashboards created via the API can be saved in the UI (unlike provisioned ones), which is both flexibility and a source of drift.
  3. Alerting resources: created via the provisioning API with a provenance marker; the UI shows “Provisioned” and they cannot be edited; if the UI really must edit them, set disable_provenance = true (this loses the guarantee that only code can change them).
  4. Notification policies: grafana_notification_policy They manage the entire policy tree (one per org); module 4's file provisioning policies is mutually exclusive with it.

When: decision matrix

ScenarioRecommendation
In-cluster Grafana, dashboards shipped with applicationsConfigMap + sidecar (module 4)
Managed / external Grafana; need permissions, teams, service accountsTerraform provider
Kubernetes-native; want to manage Grafana with CRsGrafana Operator (not covered in this lesson)
Many similar dashboardsGenerate JSON with Grafonnet or the Foundation SDK, then deploy via any of the above
Push / pull resources from the command lineGrafana CLI (grafanactl, v0.1.x); Grafana docs mark Grizzly as “removed and no longer supported”
Common misconceptions① “Dashboards managed by Terraform can't be changed in the UI”—they can be changed and saved (they are not provisioned); they're just overwritten at the next apply. Rely on process and plan drift detection. ② “Grafonnet is Grafana's officially recommended approach”—the repo README marks it experimental, and the Grafana “as code” docs state it isn't officially supported and recommend the Foundation SDK; this lesson still covers it because many existing projects (kubernetes-mixin and other monitoring mixins) are based on Jsonnet. ③ “The provider's auth can be written in code”—the token must come from an environment variable GRAFANA_AUTH or secret management. ④ “The same dashboard can be managed by both a ConfigMap and Terraform”—they overwrite each other; a uid can have only one owner.

Pipeline: from Jsonnet to Grafana

grafonnet/*.jsonnetFunctions · loops · libraries jsonnet -J vendorjb manages vendor/ dashboards/build/myapp-overview.json terraform plan / applygrafana_dashboard.config_json = file() Grafana HTTP APIPOST /api/dashboards/db/api/v1/provisioning/contact-points …Authorization: Bearer glsa_… Grafana (kps or managed)Folder platform-tfDashboard myapp-overviewContact point / rule group (provenance=api) terraform.tfstateRecords uid, versionRemote backend + lockContains sensitive values → encrypted storage
Figure 5-1 Generation (Jsonnet) and deployment (Terraform) are separated; in CI both steps can be validated before execution

Ownership: three kinds of resources in the same Grafana

SourceSaveable in UIHow drift is detectedExample in this lesson
File provisioning / sidecarDashboards: no (allowUiUpdates: false); alerting resources: noNo drift (restored on every scan)myapp-red (module 4)
Terraform (API)Dashboards: yes; alerting resources: no (unless disable_provenance)terraform planmyapp-overview,oncall-webhook
Manual UIYesNoneExploration only

Interactive: Terraform vs. Grafana state comparison

Click the actions in order and watch how Git, build artifacts, Terraform state and Grafana's actual state change, as well as the terraform plan output.

Start from ①.
$ # output

Core commands

CommandPurposeNotes
jb init && jb install github.com/grafana/grafonnet/gen/grafonnet-latest@mainInstall Grafonnet into vendor/Generates jsonnetfile.json / jsonnetfile.lock.json, pinning the commit
jsonnet -J vendor grafonnet/myapp-overview.jsonnet -o dashboards/build/myapp-overview.jsonGenerate JSONgo-jsonnet recommended (the C implementation has performance issues)
jsonnetfmt --test grafonnet/*.jsonnetFormat checkUse in CI
terraform init / plan / applyDeployGRAFANA_URL,GRAFANA_AUTH environment variables
terraform import grafana_dashboard.x <uid>Take over existing resourcesor use the import block

1. Create a service account and token for Terraform (one-time bootstrap)

PW=$(kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d)
SA_ID=$(curl -s -u admin:$PW -H 'Content-Type: application/json' \
  -X POST localhost:3000/api/serviceaccounts -d '{"name":"terraform","role":"Admin"}' | jq .id)
export GRAFANA_AUTH=$(curl -s -u admin:$PW -H 'Content-Type: application/json' \
  -X POST localhost:3000/api/serviceaccounts/$SA_ID/tokens -d '{"name":"tf-lab","secondsToLive":86400}' | jq -r .key)
export GRAFANA_URL=http://localhost:3000
echo ${GRAFANA_AUTH:0:5}…
glsa_…

Security: Keep the token only in environment variables / CI secrets, and set an expiry (1 day here). In production, grant a minimal role (Editor or fine-grained RBAC), and use Admin only when you must manage service accounts / teams.

2. Grafonnet: myapp overview dashboard

local g = import 'github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet';
local ts = g.panel.timeSeries;
local stat = g.panel.stat;
local prom = g.query.prometheus;

local ds = 'prometheus';            // kps's default data source uid
local sel = 'namespace="myapp"';

// A reusable “time series panel” function: the same pattern can generate panels for 20 services
local tsPanel(title, expr, unit, legend) =
  ts.new(title)
  + ts.queryOptions.withTargets([prom.new(ds, expr) + prom.withLegendFormat(legend)])
  + ts.standardOptions.withUnit(unit)
  + ts.gridPos.withW(12) + ts.gridPos.withH(8);

g.dashboard.new('myapp / overview (terraform)')
+ g.dashboard.withUid('myapp-overview')
+ g.dashboard.withTags(['myapp', 'generated', 'terraform'])
+ g.dashboard.withRefresh('30s')
+ g.dashboard.time.withFrom('now-3h')
+ g.dashboard.withPanels(
  g.util.grid.wrapPanels([
    stat.new('Online instances')
    + stat.queryOptions.withTargets([prom.new(ds, 'sum(up{%s,job="myapp"})' % sel)])
    + stat.gridPos.withW(6) + stat.gridPos.withH(4),
    stat.new('Redis connections')
    + stat.queryOptions.withTargets([prom.new(ds, 'min(myapp_redis_up{%s})' % sel)])
    + stat.gridPos.withW(6) + stat.gridPos.withH(4),
    tsPanel('Request rate (by status code)',
            'sum by (status) (rate(myapp_http_requests_total{%s}[$__rate_interval]))' % sel,
            'reqps', '{{status}}'),
    tsPanel('P95 latency (recording rule)',
            'myapp:http_request_duration_seconds:p95_5m{%s}' % sel,
            's', 'p95'),
  ], panelWidth=12, panelHeight=8)
)
cd ~/promlab/monitoring-config
jb init
jb install github.com/grafana/grafonnet/gen/grafonnet-latest@main
mkdir -p dashboards/build
jsonnet -J vendor grafonnet/myapp-overview.jsonnet -o dashboards/build/myapp-overview.json
jq '{uid, title, panels: [.panels[] | {type, title, gridPos}]}' dashboards/build/myapp-overview.json
{
  "uid": "myapp-overview",
  "title": "myapp / overview (terraform)",
  "panels": [
    {"type": "stat", "title": "Online instances", "gridPos": {"h": 4, "w": 6, "x": 0, "y": 0}},
    {"type": "stat", "title": "Redis connections", "gridPos": {"h": 4, "w": 6, "x": 6, "y": 0}},
    {"type": "timeseries", "title": "Request rate (by status code)", "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}},
    ...
  ]
}

wrapPanels keeps each panel's own w/h (falls back to panelWidth/panelHeight when unset), lays panels out in 24 columns and computes x/y; makeGrid would force all panels to the same size. In jsonnet strings, the % is the formatting operator; {{status}} is left as-is for Grafana. To also commit vendor/ to Git for offline builds, commit jsonnetfile.lock.json and you can reproduce the same version.

3. Terraform

terraform {
  required_version = ">= 1.17.0"
  required_providers {
    grafana = {
      source  = "grafana/grafana"
      version = "~> 4.55"
    }
  }
}

# url and auth come from environment variables GRAFANA_URL / GRAFANA_AUTH
provider "grafana" {}

variable "webhook_url" {
  type      = string
  sensitive = true
}

resource "grafana_folder" "platform" {
  uid   = "platform-tf"
  title = "platform (terraform)"
}

resource "grafana_dashboard" "myapp_overview" {
  folder      = grafana_folder.platform.uid
  config_json = file("${path.module}/../../dashboards/build/myapp-overview.json")
  overwrite   = true
  message     = "managed by terraform"
}

resource "grafana_contact_point" "oncall" {
  name = "oncall-webhook"
  webhook {
    url = var.webhook_url
  }
}

# the whole notification policy tree (one per org). If you already defined policies with file provisioning in module 4, keep only one of the two.
resource "grafana_notification_policy" "root" {
  contact_point   = grafana_contact_point.oncall.name
  group_by        = ["grafana_folder", "alertname"]
  repeat_interval = "4h"
  policy {
    matcher {
      label = "severity"
      match = "="
      value = "critical"
    }
    contact_point = grafana_contact_point.oncall.name
    group_wait    = "10s"
  }
}

resource "grafana_rule_group" "myapp" {
  name             = "myapp-tf"
  folder_uid       = grafana_folder.platform.uid
  interval_seconds = 60
  rule {
    name      = "MyappNoTraffic"
    condition = "C"
    for       = "10m"
    labels    = { severity = "warning" }
    annotations = {
      summary           = "myapp has had no requests for 10 minutes"
      __dashboardUid__ = grafana_dashboard.myapp_overview.uid
      __panelId__      = "3"
    }
    data {
      ref_id         = "A"
      datasource_uid = "prometheus"
      relative_time_range {
        from = 600
        to   = 0
      }
      model = jsonencode({ refId = "A", expr = "sum(rate(myapp_http_requests_total{namespace=\"myapp\"}[5m]))", instant = true })
    }
    data {
      ref_id         = "C"
      datasource_uid = "__expr__"
      relative_time_range {
        from = 0
        to   = 0
      }
      model = jsonencode({
        refId = "C", type = "threshold", expression = "A",
        conditions = [{ evaluator = { type = "lt", params = [0.01] } }]
      })
    }
  }
}

output "dashboard_url" { value = grafana_dashboard.myapp_overview.url }
cd terraform/grafana
export TF_VAR_webhook_url=http://alert-sink.monitoring.svc:8080/hook
terraform init
terraform plan -out tfplan
terraform apply tfplan
Terraform will perform the following actions:
  # grafana_contact_point.oncall will be created
  # grafana_dashboard.myapp_overview will be created
  # grafana_folder.platform will be created
  # grafana_notification_policy.root will be created
  # grafana_rule_group.myapp will be created
Plan: 5 to add, 0 to change, 0 to destroy.
...
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
Outputs:
dashboard_url = "http://localhost:3000/d/myapp-overview/myapp-overview-terraform"

How to verify: Grafana → Dashboards → platform (terraform); in Alerting → Alert rules, MyappNoTraffic carries the “Provisioned” marker. Common mistakes: Panel id and __panelId__ do not correspond (dashboard.withPanels ids are assigned in order; after generating, use jq '.panels[] | {id,title}' to confirm). Production use: Remote state (S3 / Azure Storage + locking); in CI, plan comment on the PR; after merging, apply.

Goal: generate the dashboard with Grafonnet, deploy it to kps's Grafana with Terraform, and hands-on create, detect and fix drift. Environment: module 4; Terraform 1.17.x; go-jsonnet and jb. No cloud cost.
(Optional) fake webhook receiver: for contact point testing.
kubectl -n monitoring run alert-sink --image=mendhak/http-https-echo:latest --port=8080 --expose
kubectl -n monitoring logs -f pod/alert-sink   # watch in another terminal

The image is a community echo service for lab use only; check Docker Hub for the tag.

Build and deploy: run steps 1–3 of the “Command” page. Confirm that terraform plan the second run shows No changes..
Create drift: in the UI, open “myapp / overview (terraform)”, change a panel title and save (saving is allowed; it is not provisioned).
terraform plan
  # grafana_dashboard.myapp_overview will be updated in-place
  ~ resource "grafana_dashboard" "myapp_overview" {
      ~ config_json = jsonencode(
          ~ {
              ~ panels = [
                  ~ {
                      ~ title = "Online instances (changed in UI)" -> "Online instances"
...
Plan: 0 to add, 1 to change, 0 to destroy.
Run terraform apply to revert it.
Try, in the UI, editing the contact point: confirm that it is rejected or read-only (provenance).
Change via code: in jsonnet, add a “5xx ratio” panel → rebuild → plan shows only the config_json change → apply.
Add to CI (same workflow as module 6): jsonnetfmt --test, build the JSON and git diff --exit-code dashboards/build (ensure build output is committed),terraform fmt -check,terraform validate.
Cleanup: terraform destroy (delete the folder, dashboard, contact point and rule group, and reset the notification policy to default); delete the service account: curl -X DELETE -u admin:$PW localhost:3000/api/serviceaccounts/$SA_ID; kubectl -n monitoring delete pod,svc alert-sink.

Case 1: one RED template for 20 microservices

Problem: Each service has its own copy-pasted JSON; changing one query means editing 20 places. Approach: Jsonnet function red(service) generates panels,std.map iterates over the service list; or adopt the monitoring mixin structure (mixin.libsonnet simultaneously exporting prometheusAlerts,prometheusRules,grafanaDashboards), with rules and dashboards sharing the same set of selectors. Limitations: The team needs to know Jsonnet; for new projects, evaluate the Foundation SDK (in a language the team knows).

Case 2: managed Grafana “click-ops” configuration cannot be copied to a new region

Problem: Data sources and contact points configured by hand in Azure Managed Grafana were missed when rebuilding in the disaster-recovery region. Approach: Terraform creates both the workspace (azurerm) and the resources in it (grafana provider,url pointing to the workspace endpoint, with the token issued by a service account); the two providers are kept in separate states, so the grafana provider cannot fail to initialize before the workspace is ready.

Case 3: secrets in state

Problem: Contact point webhook URLs and data source passwords are stored in plaintext in state. Approach: Encrypt remote state and enforce strict access control; mark variables sensitive; for resources that support write-only / ephemeral mechanisms, use them per the Terraform and provider docs (the official docs prevail).

Common errors and fixes

Error: status: 401, body: {"message":"Invalid API key"} / {"message":"Unauthorized"}

Cause:GRAFANA_AUTH is empty, the token has expired, or the service account was deleted; or the URL points to another Grafana.

curl -s -H "Authorization: Bearer $GRAFANA_AUTH" $GRAFANA_URL/api/user | jq .login
Error: status: 412 … "The dashboard has been changed by someone else" / version-mismatched

Cause: A dashboard with the same uid already exists (for example, imported by hand earlier, or provided by a ConfigMap).

Fix: Confirm there is a single owner; when Terraform takes over, set overwrite = true or first terraform import; if this uid is provided by the sidecar, change the uid or delete the ConfigMap.

RUNTIME ERROR: couldn't open import "github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet": no match locally or in the Jsonnet library paths

Cause: Did not run jb install, or forgot -J vendor.

ls vendor/github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet
jsonnet -J vendor grafonnet/myapp-overview.jsonnet > /dev/null && echo OK
Error: … cannot update provisioned resource / "Provenance" mismatch when updating notification policy

Cause: This resource (or the entire notification policy tree) is already defined by file provisioning (optional step in module 4); provenance is file, so the API cannot modify it.

Fix: Choose one: remove the policies from the provisioning file (and reload), or do not manage notification policies in Terraform.

Every plan shows a config_json change (never converges)

Cause: The JSON contains fields that Grafana rewrites (id,version, or an old schemaVersion gets migrated); field order in jsonnet-generated JSON does not matter, but content differences do.

Fix: Remove id/version from the JSON; use a newer schemaVersion; compare terraform plan the specific fields in it and fix them at the source.

Command-line exercise
1. Bring the dashboard that already exists in the UI, with uid legacy-api, under Terraform management (Terraform 1.5+ import block).
import {
  to = grafana_dashboard.legacy
  id = "legacy-api"
}
resource "grafana_dashboard" "legacy" {
  config_json = file("dashboards/legacy-api.json")   # first export via the API: curl …/api/dashboards/uid/legacy-api | jq .dashboard
}

The import ID format follows the Import section of the provider docs (with multiple orgs, you may need orgID:uid).

2. In CI, confirm that the jsonnet build output is committed.
for f in grafonnet/*.jsonnet; do jsonnet -J vendor "$f" -o "dashboards/build/$(basename "${f%.jsonnet}").json"; done
git diff --exit-code dashboards/build
Scenario analysis question
The team has Grafana inside kps (dev cluster) and Azure Managed Grafana (production). They want the same set of dashboards on both sides, with production alerts owned by Prometheus rules. Design the repository and pipeline.

Source: grafonnet/ (or the Foundation SDK) generates dashboards/build/*.json, fixed uids; data sources use template variables or a uid agreed in both environments (dev: prometheus, production creates an Azure Monitor managed Prometheus data source with the same uid in AMG). Dev cluster: package the build output into a ConfigMap (kustomize configMapGenerator + labels), synced by GitOps. Production: Terraform (azurerm creates the workspace; grafana provider manages folders, dashboards, data sources and permissions); plan on the PR, apply after merge. Alerts: PrometheusRule (dev) and the managed Prometheus rule groups (production, lesson 3) share the same rule source file, with promtool tests run uniformly in CI; Grafana-managed alerts are used only for scenarios that need multiple data sources.

Verified teaching videos

▶
Part 1: Observability as Code with Grafana Foundation SDK | Grafana 12 | Grafana Labs — Grafana
English · Foundation SDK (the official alternative to Grafonnet)
▶
Grafana Provider in Terraform | #1 — Let's Learn Devops
English · provider introduction (older version; resource parameters per the v4.55.0 docs)
▶
Mixing Azure And Grafana In A Terraform Provider Mashup! — Azure Terraformer
English · azurerm + grafana dual providers (corresponds to production case 2)

No verified dedicated video was found for Grafonnet; see the storyboard script below.

Official documentation

Video storyboard script (about 75 seconds)

This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.

Shot 1 · 0–25s
Scene: on the left, a Jsonnet function tsPanel; on the right, panels for twenty services are stamped out in batches like seals and merged into one JSON file.
Narration: Grafonnet uses functions to generate dashboards; change one place and all twenty services update together.
Shot 2 · 25–50s
Scene: terraform plan lists five resources; after apply, the folder, dashboard and contact point appear in Grafana, and the rules are marked Provisioned.
Narration: Terraform manages Grafana through the API; alerting resources are locked so that only code can change them.
Shot 3 · 50–75s
Scene: someone changes a title in the UI; the plan shows red/green differences; after apply, it's restored.
Narration: when a dashboard is edited by hand, plan detects the drift, and apply changes it back to what the code describes.
or score ≥ 70% in the “Quiz”

Module 6 · Rule testing: promtool and CI

35:00 – 42:00 · The admission webhook only checks syntax; whether an alert fires at the right time and whether its labels and annotations are correct must be checked with promtool test rules — replay rules on synthetic time series and assert, like unit tests
7 minpromtool 3.16.0test rules · check rules · --junit--diff is experimental★★★★★
Learning objectives
  • Write promtool test files: rule_files,evaluation_interval,tests[].input_series (a+bxn,axn,_,stale),alert_rule_test,promql_expr_test.
  • Accurately work out for and eval_time relationship (when it is pending and when it fires), and write negative tests for “should not fire”.
  • Convert PrometheusRule into a native rule file and test it, and in GitHub Actions run check rules + test rules, producing a JUnit report.
Prerequisites: Module 2's myapp-rules; lesson 1 rate() and extrapolation; lesson 2's alert lifecycle. Importance:★★★★★

What: promtool's three rule-related subcommands

CommandWhat it checksWhat it cannot find
promtool check rules FILE…YAML structure, PromQL syntax, template syntax; the default lint checks for duplicate rules (--lint,--lint-fatal makes lint problems fail with exit code 3)thresholds,for, whether labels are correct
promtool test rules TEST…Evaluates rules over time on synthetic series: whether an alert is firing at a given moment and which labels and (expanded) annotations it carries; the result of any PromQL at a given momentreal data distribution, scrape issues
promtool check configFull prometheus.yml (generated by the Operator in Operator setups; rarely used)—

Test file structure (Prometheus official docs): top level rule_files (supports glob),evaluation_interval (default 1m),group_eval_order,fuzzy_compare,tests; each test group has name,interval (default equals evaluation_interval),input_series,alert_rule_test,promql_expr_test,external_labels,external_url, and start_timestamp.

Series notationExpansionPurpose
0+60x100 60 120 … 600 (11 points in total)Steadily increasing counter (+60 per minute → rate = 1/s)
1x51 1 1 1 1 1 (a+0xn is shorthand, n+1 points)Constant gauge
10-2x310 8 6 4Decreasing
1 1 _ _ 0_ = no sample at that moment (scrape failed)Verify lookback behavior
1 1 stale 0stale = stale marker (target disappeared)Verify that the alert resets when the series disappears

Why: why alerts need unit tests

  • The cost of wrong alerts is asymmetric: false positives cause fatigue; false negatives equal no monitoring, and they are only discovered during an incident.
  • Common logic errors Only time-dimension tests can catch: for too long, which causes brief failures to be ignored,sum drops the namespace label that routing needs, a ratio with a zero denominator returns no result, and an annotation template references a label that does not exist.
  • Safe refactoring: after renaming a recording rule or changing its expression, tests guarantee that the behavior of alerts depending on it stays the same.

How: timeline calculation (you must be able to do it by hand)

  1. Sample time: the k-th value is at start_timestamp + k × interval (starts from 0 by default; with a 1m interval → 0m, 1m, 2m …).
  2. Rules are evaluated at every evaluation_interval evaluation; at eval_time the assertion time, promtool has evaluated in order up to that moment.
  3. The evaluation moment when the alert expression is first true is recorded as activeAt, state pending; when eval_time − activeAt ≥ for is reached, it is firing; if the expression is false (or has no result) midway, it resets.
  4. Example: up = 1 1 1 0 0 0 0,for: 2m → true from 3m (pending),5m fires from; at the 4m assertion, write exp_alerts: [] (pending does not count as firing).
  5. The lookback window of an instant selector defaults to 5m: _ (when the sample is missing), it takes the most recent value within 5 minutes; stale otherwise it immediately yields “no value”.
  6. exp_labels You must write out the alert's complete labels (excluding alertname) and exp_annotations write the expanded annotations in full; writing extra or missing ones both fail. When several rules share an alert name, list the union of all firing instances in one test case.

When: where to run

  • Locally: before committing, run promtool test rules rules/tests/*.yml.
  • PR: check + test (fast, seconds); a failure blocks merging; the JUnit report appears in CI test results.
  • Cluster: the admission webhook does another syntax check (module 2); PrometheusRuleFailures,PrometheusBadConfig and default alerts catch runtime issues as a fallback.
  • Optional: use pint connected to a real Prometheus to check whether “metrics referenced by rules actually exist”.
Common misconceptions① “Passing check rules is enough”—it evaluates no data. ② “The PrometheusRule YAML can be fed directly to promtool”—no; you must extract .spec (yq '.spec') becomes groups: a native rule file starting with it. ③ “eval_time equal to for will fire”—it counts from the first time the expression is true, not from 0. ④ “exp_labels only need the ones I care about”—they must match exactly; forgetting severity or pod fails. ⑤ “The rate value is hard to assert”—choose a series whose extrapolated result is an integer (e.g. +60 per minute), or enable fuzzy_compare.

Timeline: MyappDown (for: 2m)

0m1m2m3m4m5m6m7m up 10 inactive pending (activeAt = 3m) firing (5m − 3m ≥ 2m) eval_time 4m → exp_alerts: []eval_time 5m/6m → 1 alert
Figure 6-1 values: '1 1 1 0 0 0 0 0', interval 1m; the alert starts timing from the first time the expression is true

Pipeline: rule checks in the PR

PrometheusRulemanifests/** yq '.spec'build/*.rules.yml check rulesSyntax + lint test rules--junit report Merge → Argo CDwebhook re-validation
Figure 6-2 The PrometheusRule remains the single source of truth; the tests use the native rule files extracted from it

Interactive: alert unit test timeline

Select the input series and for, then drag eval_time, and observe the value and alert state at each evaluation time, plus how the expected assertion at that moment exp_alerts should be written. The simulation follows Prometheus rule evaluation logic (including the 5-minute lookback and stale markers).

for:

Core commands

CommandPurposeNotes
yq '.spec' manifests/myapp/prometheusrule.yaml > build/myapp.rules.ymlCRD → native rule fileMulti-document YAML with yq ea
promtool check rules build/*.rules.ymlSyntax + lint--lint=all --lint-fatal Stricter
promtool test rules rules/tests/*.test.ymlUnit testsRun multiple files at once
promtool test rules --run 'MyappDown' …Run only matching test groupsRegex, repeatable
promtool test rules --diff …Show expected vs. actual differences in colorExperimental
promtool test --junit=build/junit.xml rules …Output JUnit XML--junit Yes test Command arguments

1. Test file

rule_files:
  - ../../build/myapp.rules.yml       # relative to this test file
evaluation_interval: 1m

tests:
  # ---------- MyappDown: for 2m ----------
  - name: MyappDown pending then firing
    interval: 1m
    input_series:
      - series: 'up{job="myapp", namespace="myapp", pod="myapp-a"}'
        values: '1 1 1 0 0 0 0 0'
      - series: 'up{job="myapp", namespace="myapp", pod="myapp-b"}'
        values: '1x7'
    alert_rule_test:
      - eval_time: 4m                  # true from 3m; still pending here
        alertname: MyappDown
        exp_alerts: []
      - eval_time: 5m
        alertname: MyappDown
        exp_alerts:
          - exp_labels: {severity: critical, job: myapp, namespace: myapp, pod: myapp-a}
            exp_annotations:
              summary: "myapp instance myapp-a scrape failed"

  # ---------- High error rate: 25% > 5% ----------
  - name: MyappHighErrorRate fires at 25 percent
    interval: 1m
    input_series:
      - series: 'myapp_http_requests_total{namespace="myapp", method="GET", route="/", status="200"}'
        values: '0+45x20'              # rate = 0.75/s
      - series: 'myapp_http_requests_total{namespace="myapp", method="GET", route="/", status="500"}'
        values: '0+15x20'              # rate = 0.25/s
    alert_rule_test:
      - eval_time: 12m
        alertname: MyappHighErrorRate
        exp_alerts:
          - exp_labels: {severity: warning, namespace: myapp}
            exp_annotations:
              summary: "myapp 5xx ratio 25%"
    promql_expr_test:
      - expr: myapp:http_requests:rate5m
        eval_time: 12m
        exp_samples:
          - labels: 'myapp:http_requests:rate5m{namespace="myapp", route="/", status="200"}'
            value: 0.75
          - labels: 'myapp:http_requests:rate5m{namespace="myapp", route="/", status="500"}'
            value: 0.25

  # ---------- Negative test: 2% should not alert ----------
  - name: MyappHighErrorRate silent at 2 percent
    interval: 1m
    input_series:
      - series: 'myapp_http_requests_total{namespace="myapp", method="GET", route="/", status="200"}'
        values: '0+294x20'
      - series: 'myapp_http_requests_total{namespace="myapp", method="GET", route="/", status="500"}'
        values: '0+6x20'
    alert_rule_test:
      - eval_time: 15m
        alertname: MyappHighErrorRate
        exp_alerts: []

  # ---------- Redis disconnected: for 1m ----------
  - name: MyappRedisDown
    interval: 1m
    input_series:
      - series: 'myapp_redis_up{namespace="myapp", pod="myapp-a"}'
        values: '1 1 0 0 0'
    alert_rule_test:
      - eval_time: 4m
        alertname: MyappRedisDown
        exp_alerts:
          - exp_labels: {severity: critical, namespace: myapp, pod: myapp-a}
            exp_annotations:
              summary: "myapp cannot connect to Redis (myapp-a)"

  # ---------- Selector mismatch: no up series at all ----------
  - name: MyappTargetMissing
    interval: 1m
    input_series:
      - series: 'up{job="other", namespace="other"}'
        values: '1x10'
    alert_rule_test:
      - eval_time: 6m
        alertname: MyappTargetMissing
        exp_alerts:
          - exp_labels: {severity: critical, namespace: myapp, job: myapp}   # absent() inherits labels from equality matchers
            exp_annotations:
              summary: "myapp has no scrape targets"
              description: "Check the ServiceMonitor release label and selector (Module 2)."

Why rate is exactly 0.75: +45 per minute; the 5-minute window (left-open, right-closed) holds 5 samples spanning 4 minutes, an increase of 180; the first sample is 1 minute after the window start (within 1.1× the average interval), so it extrapolates to the full 5 minutes = 225; 225 / 300 s = 0.75. Error ratio 0.25 / 1.0 = 0.25,humanizePercentage which outputs “25%”.

2. Run

cd ~/promlab/monitoring-config
mkdir -p build
yq '.spec' manifests/myapp/prometheusrule.yaml > build/myapp.rules.yml
promtool check rules build/myapp.rules.yml
promtool test rules rules/tests/myapp.test.yml
Checking build/myapp.rules.yml
  SUCCESS: 7 rules found

Unit Testing:  rules/tests/myapp.test.yml
  SUCCESS

3. Deliberately break a rule and look at the failure output

# Change MyappDown's for to 5m, then run the tests again
sed -i 's/for: 2m/for: 5m/' manifests/myapp/prometheusrule.yaml
yq '.spec' manifests/myapp/prometheusrule.yaml > build/myapp.rules.yml
promtool test rules --run 'MyappDown' rules/tests/myapp.test.yml
Unit Testing:  rules/tests/myapp.test.yml
  FAILED:
    name: MyappDown pending then firing,
    alertname: MyappDown, time: 5m,
        exp:[
            0:
              Labels:{alertname="MyappDown", job="myapp", namespace="myapp", pod="myapp-a", severity="critical"}
              Annotations:{summary="myapp instance myapp-a scrape failed"}
            ],
        got:[]
git checkout manifests/myapp/prometheusrule.yaml   # restore

4. GitHub Actions

name: rules
on:
  pull_request:
    paths: ['manifests/**', 'rules/**', '.github/workflows/rules.yaml']
permissions:
  contents: read
  checks: write          # only needed when using an action that publishes test results
jobs:
  promtool:
    runs-on: ubuntu-latest
    env:
      PROM_VERSION: "3.16.0"     # keep in sync with the Prometheus in the cluster
    steps:
      - uses: actions/checkout@v7
      - name: Install promtool
        run: |
          curl -sSfL "https://github.com/prometheus/prometheus/releases/download/v${PROM_VERSION}/prometheus-${PROM_VERSION}.linux-amd64.tar.gz" | tar xz
          sudo install "prometheus-${PROM_VERSION}.linux-amd64/promtool" /usr/local/bin/
          promtool --version
      - name: Extract rules from PrometheusRule CRs
        run: |
          mkdir -p build
          for f in $(grep -rl '^kind: PrometheusRule' manifests); do
            n=$(yq '.metadata.name' "$f")
            yq '.spec' "$f" > "build/${n%-rules}.rules.yml"
          done
          ls build
      - name: Check rules
        run: promtool check rules --lint=all --lint-fatal build/*.rules.yml
      - name: Unit test rules
        run: promtool test --junit=build/junit.xml rules rules/tests/*.test.yml
      - uses: actions/upload-artifact@v7
        if: always()
        with: {name: promtool-junit, path: build/junit.xml}

Note ${n%-rules} Change myapp-rules to myapp, so that the file name matches the ../../build/myapp.rules.yml reference in the test. In a real project, agree on one naming convention (for example, PrometheusRule name = rule file name). yq Preinstalled on GitHub-hosted Ubuntu runners; check each project's Releases for the current action major version.

Goal: write tests for myapp's 5 alerts and 1 recording rule, make them pass locally and in CI, and see a “logic error” get caught by a test. Environment: promtool 3.16.0, yq; no cluster needed.
Write the tests and run them: follow steps 1 and 2 under “Command” and confirm SUCCESS. Pay attention to the rule_files relative paths in the test file.
Introduce a logic error: in the PrometheusRule, change MyappHighErrorRate ’s sum by (namespace) to sum (looks harmless), then re-extract and run:
promtool test rules --run 'HighErrorRate' rules/tests/myapp.test.yml
Failure reason: the alert is missing namespace label. In production this would break the Alertmanager route keyed on namespace; the test caught it early. Revert the change.
Write your own test: for MyappHighLatencyP95 Construct histogram input:
      - series: 'myapp_http_request_duration_seconds_bucket{namespace="myapp", le="0.5"}'
        values: '0+0x20'
      - series: 'myapp_http_request_duration_seconds_bucket{namespace="myapp", le="1"}'
        values: '0+60x20'
      - series: 'myapp_http_request_duration_seconds_bucket{namespace="myapp", le="+Inf"}'
        values: '0+60x20'
all requests fall in (0.5, 1] → P95 ≈ 0.975 s > 0.5 s; for: 10m, so at eval_time: 12m assert firing (the exact annotation text humanizeDuration can be filled in after you check the output --diff ).
Push to CI: commit .github/workflows/rules.yaml, open a PR, confirm the promtool job passes and uploads junit.xml; then open another PR that changes the threshold to > 0.5 (the error-rate threshold) and confirm the negative test still passes and the positive test fails.
Make it a required check: in the repository's Rules, make the promtool job required before merging (GitHub course, Lesson 3). Cleanup: none needed.

Case 1: an overly long for causes missed alerts

Problem: A payment service's 5xx alert for: 15m did not fire at all during a 12-minute outage. What was done: Using promtool, they wrote a test requiring that a 10-minute outage must trigger an alert; this led the team to switch to multi-window burn-rate alerts (Lesson 6). Takeaway: Tests do more than check code; they also turn SLO expectations into executable documentation.

Case 2: a regression in kubernetes-mixin rules

Problem: After upgrading kps, the default rules changed and a custom inhibition rule no longer matched. What was done: CI renders the kps chart (helm template) → extracts all PrometheusRules → promtool check rules; tests are written for the few default alerts the team depends on (such as KubePodCrashLooping), and they run automatically in upgrade PRs.

Case 3: testing and Grafana-managed alerts

Problem: Grafana-managed alerts cannot be tested with promtool. What was done: Critical alerts are kept in Prometheus rules (testable, and unaffected by Grafana outages); Grafana-managed alerts are used only for cross-datasource or log-based scenarios, with end-to-end validation in staging.

Common errors and fixes

FAILED: … got:[] (expected firing, but no alert)

Cause: eval_time is earlier than activeAt + for; the label selector in the expression does not match input_series (for example, the rule requires namespace="myapp", but the input series has no namespace); too few samples in the rate window.

promtool test rules --debug --run 'MyappDown' rules/tests/myapp.test.yml

Use promql_expr_test to assert the value of the alert expression itself at the same time, narrowing the problem step by step.

FAILED: … exp:[0: Labels:{…severity="critical"}] got:[0: Labels:{…pod="myapp-a", severity="critical"}]

Cause: exp_labels is missing (or has extra) labels; an aggregation changed the label set.

Fix: Write out the full label set shown in got (except alertname); if the labels in got are not what you expect, fix the rule rather than the test.

Unit Testing: … FAILED: … could not parse expression / yaml: unmarshal errors: field groups not found in type …

Cause:rule_files The path points to the PrometheusRule CRD itself (the top level is apiVersion/kind, not groups), or the relative path is wrong.

head -3 build/myapp.rules.yml     # should start with groups:
exp_annotations mismatch: summary="myapp 5xx ratio 25%" vs "myapp 5xx ratio 24.99%"

Cause: rate extrapolation produces a non-integer ratio.

Fix: Choose inputs that make the extrapolation exact (per-minute increments that are multiples of 60, and test times ≥ the window length); or avoid printing the raw value directly in the annotation $value, use fixed text plus a dashboard link instead; if needed, set the top-level fuzzy_compare: true option (this only affects numeric sample comparison).

Command-line exercises
1. Run only the test groups whose names contain “Redis”, and print the expected/actual differences.
promtool test rules --run 'Redis' --diff rules/tests/myapp.test.yml
2. Write an input series: a counter starts at 100 and increases by 30 per minute for 10 minutes, and the scrape fails at minute 5 (missing sample).
values: '100 130 160 190 220 _ 280 310 340 370 400'

or '100+30x4 _ 280+30x4'.

Scenario analysis
A colleague wrote the MyappDown: up == 0, for: 2m test with input '1 1 0 0 0', asserting firing at eval_time: 2m ; the test fails. He says, “I set it to 2 minutes.” Explain and fix the test, and add a negative test.

The expression first becomes true at 2m (activeAt=2m); at that point the state is pending, and it only fires at 4m (4−2 ≥ 2). Fix: at eval_time: 4m assert firing, and at 3m assert exp_alerts: [] (negative: it must not fire during the for period). Also consider a test for a 1-minute blip that then recovers ('1 1 0 1 1') that must never fire at any point.

Verified teaching videos

▶
Lightning Talk: Prometheus rules validation one step further - Martin Chodur, Seznam — CNCF [Cloud Native Computing Foundation]
English · Advanced rule validation (beyond promtool checks)
▶
Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output) — DevOps Simplified
English · Pending/firing and hands-on promtool testing

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.

Shot 1 · 0–20s
Visual: on the timeline, a row of green dots turns red; below, the state bar changes from inactive to yellow pending, then to red firing.
Narration: the alert starts timing from the first time it is true, and only fires once the for duration is met.
Shot 2 · 20–50s
Visual: in the test file, the input_series, eval_time and exp_alerts sections are highlighted in turn; the terminal prints SUCCESS.
Narration: promtool replays the rules on synthetic data and, like a unit test, asserts the alert's labels and annotations.
Shot 3 · 50–75s
Visual: someone in a PR changes sum by namespace to sum; CI turns red, and the namespace branch on the Alertmanager routing diagram is disconnected.
Narration: a change that looks harmless drops the routing label, and the test stops it before merge.
or score ≥ 70% on the Quiz

Module 7 · Black-box monitoring: blackbox exporter and synthetic probes

42:00 – 50:00 · White-box metrics say “I think I'm fine”; black-box probing asks “can users reach it?”. Each Prometheus scrape makes the blackbox exporter probe a target, and the result comes back as probe_* metrics
8 minutesblackbox_exporter v0.29.1 · chart 11.21.3Probe CRD (monitoring.coreos.com/v1)★★★★☆
Learning objectives
  • Understand the “multi-target exporter” pattern: the target and module are passed as URL parameters /probe?target=…&module=… and relabeling replaces __address__ with the exporter address.
  • Install the blackbox exporter, define http / tcp modules, and use Probe CRs (release: kps) to probe the myapp internal address and an external HTTPS site.
  • Read probe_success,probe_http_status_code,probe_phase_duration_seconds and probe_ssl_earliest_cert_expiry, write alerts for probe failure and certificate expiry, then use debug=true to troubleshoot.
Prerequisites: Lesson 1 relabeling; the selector chain from Module 2. kps does not include the blackbox exporter, which must be installed separately. Importance:★★★★☆

What: blackbox exporter

The official Prometheus probing exporter; it supports http,tcp,icmp,dns,grpc etc. probers. It does not know on its own what to probe: whenever it is scraped, /probe it takes the module (the probe module defined in the config file) to probe target, and returns the result as the metrics of that scrape.

MetricMeaningTypical alert
probe_success1 = probe succeeded (all module conditions met)probe_success == 0 for 2m
probe_duration_secondsTotal probe duration> 2s for 10m
probe_phase_duration_seconds{phase}http phases: resolve, connect, tls, processing, transferFind whether DNS or TLS is slow
probe_http_status_codeStatus code of the last responseDiagnostic aid
probe_ssl_earliest_cert_expiryEarliest expiry time in the certificate chain (Unix seconds)< 14 days away
probe_dns_lookup_time_secondsDNS resolution time—

Why: white-box and black-box complement each other

  • myapp's myapp_http_requests_total only counts requests that reached the application; DNS errors, a Service with no endpoints, Ingress/Gateway misconfiguration, or an expired certificate can leave the app metrics looking “all fine” or with no data at all.
  • Black-box probing starts from the user's path and directly answers “can it be used?”, the most direct evidence for SLO availability (Lesson 6).
  • Probes the reachability and latency of external dependencies (payment gateways, third-party APIs), even when you cannot instrument them.

How: the real path of one probe

  1. The Operator translates the Probe CR into one job (job_name: probe/<ns>/<name>,job labels come from spec.jobName): static targets become __address__, relabeling: __address__ → __param_target,__param_target → instance,__address__ = spec.prober.url,__param_module = spec.module,metrics_path = /probe.
  2. At every interval, Prometheus sends a GET http://blackbox…:9115/probe?module=http_2xx&target=https://prometheus.io, with the timeout taken from the scrape timeout.
  3. blackbox reads the available time from the request header X-Prometheus-Scrape-Timeout-Seconds , subtracts a small margin, and uses the result as the probe timeout (never exceeding the module's timeout).
  4. http prober: resolves DNS (preferred_ip_protocol) → TCP connect → TLS handshake (records certificate expiry) → sends the request (follows redirects) → reads the response → checks status code, body regex, HTTP version, etc.
  5. Returns probe_* metrics; if any check fails → probe_success 0, but the scrape itself succeeds (up == 1). So alerts should be based on probe_success, not up.

When: what to probe and from where

  • In-cluster address (http://myapp.myapp.svc:5000/healthz): verifies the Service → Pod path and rules out Ingress.
  • Public entry point (the public domain of the Gateway / Ingress): verifies DNS, certificates and routing; best probed from outside the cluster: a blackbox in another region, or managed synthetic monitoring such as Grafana Cloud Synthetic Monitoring; otherwise the prober also fails when the whole cluster goes down.
  • Certificates: every public HTTPS endpoint should have an expiry alert.
  • Do not use blackbox probes as a replacement for application metrics: the probe tells you “it is broken”, while application metrics tell you “why”.
Common misconceptions① “When a probe fails, the target goes DOWN” — no; /probe it normally returns 200 and probe_success 0,up stays 1. ② “Just put the URL you want to probe in the targets of static_configs” — you must relabel it into __param_target and replace the address with the exporter; otherwise Prometheus will scrape the target site's /probe; the Probe CRD generates these relabelings for you. ③ “The bigger the module timeout, the better” — it is capped by scrape_timeout, and a probe that exceeds the scrape timeout is treated by Prometheus as a failed scrape. ④ “kps ships with blackbox” — the chart README says it does not.

Multi-target exporter: before and after relabeling

Probe CR → discovered target__address__ = https://prometheus.iomodule = http_2xxprober.url = blackbox-…:9115 After relabeling__param_target = https://prometheus.ioinstance = https://prometheus.io__address__ = blackbox-…:9115 Actual HTTP requestGET /probe?module=http_2xx &target=https://prometheus.ioHost: blackbox-…:9115 Inside the blackbox exporter (http prober) resolve (DNS) connect (TCP) tls (certificate expiry) processing (time to first byte) transfer + validation → probe_*
Figure 7-1 The target and module are passed to the exporter as parameters; each phase's duration becomes a phase value of probe_phase_duration_seconds

Deployment topology: where to probe from

kind cluster lab Prometheusjob blackbox-http blackbox :9115ns monitoring myapp Service:5000/healthz External HTTPS siteDNS · TLS · certificate expiry Production advice: add a probe point outside the clusterAnother region / managed synthetic monitoringStill able to alert when the whole cluster fails
Figure 7-2 In-cluster probes verify the internal path; public entry points also need a probe point independent of the cluster

Animation: phase breakdown of one probe

Choose a target scenario and play it to follow each step of Prometheus → blackbox → target, and the /probe returned metrics (excerpt, modeled on the blackbox_exporter output format).

After selecting, click “Play”.
$ # output

Core commands

CommandPurposeNotes
helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter -n monitoring --version 11.21.3 -f …InstallService blackbox-prometheus-blackbox-exporter:9115
curl 'localhost:9115/probe?target=…&module=…&debug=true'Probe manually and print debug logsFirst step in troubleshooting
kubectl get probe -AList Probe CRsAlso requires release: kps
curl localhost:9115/configView the effective module configurationConfirm the merged values result

1. Install and define modules

config:
  modules:
    http_2xx:                     # chart default module, keep
      prober: http
      timeout: 5s
      http:
        valid_http_versions: ["HTTP/1.1", "HTTP/2.0"]
        follow_redirects: true
        preferred_ip_protocol: "ip4"
    http_healthz:                 # myapp: status code 200 and body contains ok
      prober: http
      timeout: 5s
      http:
        valid_status_codes: [200]
        fail_if_body_not_matches_regexp: ["(?i)ok"]
        preferred_ip_protocol: "ip4"
    tcp_connect:                  # e.g. Redis port reachability
      prober: tcp
      timeout: 5s
resources:
  requests: {cpu: 10m, memory: 32Mi}
mkdir -p ~/promlab/monitoring-config/blackbox
# Save the values above as blackbox/values.yaml (outside manifests/, so the monitoring-config app does not sync it as a K8s manifest)
helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter \
  -n monitoring --version 11.21.3 -f ~/promlab/monitoring-config/blackbox/values.yaml --wait
kubectl -n monitoring get svc blackbox-prometheus-blackbox-exporter
kubectl -n monitoring port-forward svc/blackbox-prometheus-blackbox-exporter 9115:9115 &
curl -s 'localhost:9115/probe?target=http://myapp.myapp.svc:5000/healthz&module=http_healthz' | grep -E '^probe_(success|http_status_code|duration_seconds)'
NAME                                    TYPE        CLUSTER-IP     PORT(S)    AGE
blackbox-prometheus-blackbox-exporter   ClusterIP   10.96.45.12    9115/TCP   20s
probe_duration_seconds 0.004812
probe_http_status_code 200
probe_success 1

Note: in the shell, the URL contains &, so it must be quoted. In a GitOps setup, make it a third Argo CD Application (chart + $values/blackbox/values.yaml), the same way as the kps setup in Module 3.

2. Probe CR

apiVersion: monitoring.coreos.com/v1
kind: Probe
metadata:
  name: myapp-http
  namespace: monitoring
  labels:
    release: kps                 # kps's probeSelector also requires this label by default
spec:
  jobName: blackbox-http         # becomes the job label
  interval: 30s
  module: http_healthz
  prober:
    url: blackbox-prometheus-blackbox-exporter.monitoring.svc:9115
  targets:
    staticConfig:
      static:
        - http://myapp.myapp.svc:5000/healthz
      labels:
        service: myapp
---
apiVersion: monitoring.coreos.com/v1
kind: Probe
metadata:
  name: external-https
  namespace: monitoring
  labels:
    release: kps
spec:
  jobName: blackbox-external
  interval: 60s
  module: http_2xx
  prober:
    url: blackbox-prometheus-blackbox-exporter.monitoring.svc:9115
  targets:
    staticConfig:
      static:
        - https://prometheus.io
        - https://grafana.com
kubectl apply -f manifests/blackbox/probes.yaml
sleep 90
curl -s 'localhost:9090/api/v1/query' --data-urlencode 'query=probe_success' | jq -r '.data.result[] | [.metric.job, .metric.instance, .value[1]] | @tsv'
curl -s 'localhost:9090/api/v1/query' --data-urlencode 'query=round((probe_ssl_earliest_cert_expiry - time()) / 86400)' | jq -r '.data.result[] | [.metric.instance, .value[1]] | @tsv'
blackbox-http	http://myapp.myapp.svc:5000/healthz	1
blackbox-external	https://prometheus.io	1
blackbox-external	https://grafana.com	1
https://prometheus.io	58
https://grafana.com	71

3. Probe alerts

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: blackbox-rules
  namespace: monitoring
  labels: {release: kps}
spec:
  groups:
    - name: blackbox.alerts
      rules:
        - alert: ProbeFailed
          expr: probe_success == 0
          for: 2m
          labels: {severity: critical}
          annotations:
            summary: "Probe failed: {{ $labels.instance }} (job {{ $labels.job }})"
        - alert: ProbeSlow
          expr: avg_over_time(probe_duration_seconds[5m]) > 2
          for: 10m
          labels: {severity: warning}
          annotations:
            summary: "Probe slow: {{ $labels.instance }} average {{ $value | humanizeDuration }}"
        - alert: TLSCertExpiringSoon
          expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 14
          for: 1h
          labels: {severity: warning}
          annotations:
            summary: "{{ $labels.instance }} certificate expires in {{ $value | printf \"%.0f\" }} days"

These rules should also have promtool tests (Module 6). For example, probe_ssl_earliest_cert_expiry input '864000x60' (fixed at day 10), and at eval_time assert firing after 1h (time() timing starts from 0 in the test).

Goal: use black-box probing to find a fault that “application metrics can't see”. Environment: Modules 1–6; blackbox installed in monitoring. External probing requires the cluster to reach the public internet.
Install and Probe: follow steps 1–3 under “Command”, commit manifests/blackbox/, let Argo CD sync it; in Prometheus → Targets, you should see probe/monitoring/myapp-http/… and probe/monitoring/external-https/…, all UP.
Create a state where “all Pods are healthy but the Service is unreachable”: break the myapp Service's selector — the Pods keep running,/healthz and still return ok inside the Pod:
kubectl -n myapp patch svc myapp --type merge -p '{"spec":{"selector":{"app.kubernetes.io/name":"myapp-typo"}}}'
Observe: probe_success{job="blackbox-http"} becomes 0 (connection refused / no endpoints), and ProbeFailed fires after about 2 minutes; at the same time, ServiceMonitor also discovers targets through the Service endpoints, so the up{job="myapp"} series disappears → Module 2's MyappTargetMissing fires after 5 minutes. The two alerts corroborate each other: the problem is at the Service layer, not in the application itself.
Locate with debug mode:
curl -s 'localhost:9115/probe?target=http://myapp.myapp.svc:5000/healthz&module=http_healthz&debug=true' | sed -n '1,25p'
Logs for the probe:
... level=INFO msg="Beginning probe" probe=http timeout_seconds=5
... level=INFO msg="Resolving target address" target=myapp.myapp.svc ip_protocol=ip4
... level=INFO msg="Resolved target address" target=myapp.myapp.svc ip=10.96.120.33
... level=INFO msg="Making HTTP request" url=http://10.96.120.33:5000/healthz host=myapp.myapp.svc:5000
... level=ERROR msg="Error for HTTP request" err="Get \"http://10.96.120.33:5000/healthz\": dial tcp 10.96.120.33:5000: connect: connection refused"
... level=ERROR msg="Probe failed" duration_seconds=0.0019

Metrics that would have been returned:
probe_success 0
Restore: argocd app sync monitoring-config (or selfHeal reverts the Service automatically, provided the myapp manifests are also managed by Argo CD; otherwise kubectl apply -f manifests/myapp/app.yaml). The alerts resolve one by one.
Certificate alert (optional): temporarily change the TLSCertExpiringSoon threshold to < 90, and check whether the external site triggers it (depends on how many days its certificate has left), then change it back.
Cleanup: keep blackbox and Probe (Lesson 6 uses probe_success to compute the availability SLO).

Case 1: a site-wide outage caused by an expired certificate

Problem: A manually renewed wildcard certificate expired. All Pods were healthy and all white-box metrics looked normal, but every user got errors. What was done: All public domains were added as Probes (discovered from Ingress/Gateway or generated from manifests), with a TLSCertExpiringSoon alert at 14 days and critical at 3 days; certificates are now renewed automatically by cert-manager, and probes serve as the last line of defense.

Case 2: the prober itself went down

Problem: The blackbox Pod was evicted, and all probe_success series disappeared, with no alert. What was done:absent(probe_success{job="blackbox-external"}) an absent-series alert was added; the blackbox deployment runs 2 replicas (each scrape hits only one, so results are unaffected); critical entry points also get probes from outside the cluster.

Case 3: probes causing an alert storm

Problem: The external API occasionally jitters for 1–2 seconds, the module timeout is 1s,for: 0, so alerts fire frequently. What was done: timeout is set to a reasonable value within scrape_timeout (5s),for: 2m, or based on success rate: avg_over_time(probe_success[10m]) < 0.9; and split “latency” and “availability” into two separate alerts.

Common errors and fixes

probe_success 0, debug log: Invalid HTTP response status code, wanted 2xx status_code=503

Cause: The target returns a non-2xx status (http_2xx accepts 2xx by default). It may be a real failure, or the health check endpoint may require authentication / redirect to a login page.

Fix: For real failures, troubleshoot the application; if 401/302 is expected, adjust the module valid_status_codes,follow_redirects or use a health endpoint that does not require authentication.

Error resolving address … lookup myapp.myapp.svc on 10.96.0.10:53: no such host

Cause: The target is wrong (namespace, Service name); or an in-cluster domain is being probed from outside the cluster.

kubectl -n monitoring exec deploy/blackbox-prometheus-blackbox-exporter -- nslookup myapp.myapp.svc 2>/dev/null || kubectl run -it --rm dns --image=busybox:1.36 --restart=Never -- nslookup myapp.myapp.svc
/targets shows probe/… as DOWN: context deadline exceeded

Cause: The probe takes longer than scrape_timeout (the module timeout is larger than the scrape timeout, or the Probe's scrapeTimeout is too short), so Prometheus abandons the scrape — and at that point not even probe_success is produced.

Fix: Ensure module timeout < Probe scrapeTimeout ≤ interval; use debug mode to see which phase is slow.

The Probe has been created, but Targets has no probe/monitoring/…

Cause: Same as ServiceMonitor: missing release: kps (probeSelector).

kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus -o jsonpath='{.spec.probeSelector}{"\n"}'
kubectl -n monitoring get probe --show-labels
debug log: Body did not match regular expression regexp=(?i)ok

Cause: The health endpoint returns 200 but the content is not what was expected (for example, a maintenance page, or a JSON status of degraded). This is exactly why body validation matters.

kubectl -n myapp exec deploy/myapp -- python -c "import urllib.request;print(urllib.request.urlopen('http://localhost:5000/healthz').read())"
Command-line exercises
1. Use PromQL to find the 3 external targets with the longest TLS handshake time.
topk(3, probe_phase_duration_seconds{job="blackbox-external", phase="tls"})
2. Test the Redis port manually in debug mode (tcp_connect module).
curl -s 'localhost:9115/probe?target=redis.myapp.svc:6379&module=tcp_connect&debug=true' | grep -E 'msg=|probe_success'
Scenario analysis
The boss asks: “Grafana shows myapp's error rate at 0%, so why are customers saying the site won't open?” How would you answer using this module's tools, and how would you prevent it from happening again?

A 0% error rate can mean the requests never reached the application (DNS, certificates, Gateway/Ingress, a Service with no endpoints, CDN) — application metrics only see requests that arrive. First check the public entry point's probe_success and probe_phase_duration_seconds / debug logs to locate the failing phase; then compare against the Service endpoints and Ingress configuration. Prevention: probe both the public domain and the in-cluster address, alert on certificate expiry, add a probe point outside the cluster, use a probe_success-based availability SLO (Lesson 6), and place black-box and white-box metrics side by side on the dashboard.

Verified teaching videos

▶
Monitoring Websites with Blackbox Exporter Prometheus | Prometheus Synthetic Monitoring | Helm — Bhoopesh Sharma
English · Installing blackbox with Helm and probing a website
▶
How to Configure the Prometheus Blackbox Exporter — House of Logic blog
English · Modules and relabeling configuration
▶
How To Manage Checks With Terraform | Grafana Cloud Synthetic Monitoring — Grafana
English · Managed synthetic monitoring + Terraform (one option for a probe point outside the cluster)

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.

Shot 1 · 0–20s
Visual: the application dashboard is all green, while next to it a user's browser shows “certificate has expired”.
Narration: white-box metrics only see requests that reach the app; to see the world as users do, you need black-box probing.
Shot 2 · 20–50s
Visual: Prometheus sends a probe request with a target parameter; blackbox lights up the DNS, TCP, TLS and HTTP phases in turn, and returns probe_success.
Narration: on every scrape, blackbox walks the user's access path for you.
Shot 3 · 50–75s
Visual: the TLS phase shows 9 days left on the certificate, and the alert panel lights up yellow.
Narration: certificate expiry, DNS errors and connection timeouts all trigger alerts before users notice them.
or score ≥ 70% on the Quiz

Module 8 · First five hours: recap, self-test and cleanup

50:00 – 60:00 · Tie Lessons 1–5 into one line: instrumentation → scraping → rules → alerts → visualization → cloud → codification; review this lesson's most common failures with a troubleshooting tree; keep the kind environment for Lessons 6 and 7
10 minutesReview of Lessons 1–5Keep the cluster lab for Lessons 6 and 7★★★★☆
Learning objectives
  • Be able to draw the end-to-end “monitoring as code” pipeline and name the verification method at each stage (CI, admission, reconciliation, probing, alerting).
  • Use the interactive troubleshooting tree to locate, within 2 minutes, the 6 typical failures in this lesson (target missing, rules not taking effect, GitOps sync failure, dashboard not loading, Terraform drift/permissions, probe failure).
  • Know which resources to keep for Lessons 6 and 7, which can be cleaned up, and the full cleanup order (delete CRDs last).
Prerequisites: Modules 1–7. Importance:★★★★☆

What: knowledge map of the first five hours

LessonTopicCore outputIts “as code” form in this lesson
Lesson 1Prometheus architecture, metric types, PromQL, Grafana basicsmyapp /metrics,prometheus.yml, RED dashboardsServiceMonitor generates scrape_configs; dashboard ConfigMap / Grafonnet
Lesson 2Alerting rules, Alertmanager, production readinessrules/*.yml, routing and inhibitionPrometheusRule + promtool unit tests
Lesson 3Azure Monitor managed Prometheus + Azure Managed GrafanaManaged collection and storage (CRD group azmonitoring.coreos.com)Terraform grafana provider manages resources in AMG
Lesson 4AMP + AMGManaged scraper, remote_write SigV4Same as above; rule groups are tested from the same source files
Lesson 5 (this lesson)Operator, GitOps, monitoring as codemonitoring-config repository—
Lesson 6(next lesson)Architecture in practice: Thanos / Mimir, multi-cluster, SLOsExtend on this lesson's kind environmentadd a Thanos sidecar / remote_write to the kps values; SLO rules are likewise tested with promtool

Why: why codify every layer

In the first four lessons you did everything in the UI and in single config files; in production, the real risk comes from change: new services being onboarded, threshold tweaks, upgrades, migrations, multi-cluster replication. This lesson turns every layer into “text in Git + automated verification + controller reconciliation”, so any change can be reviewed, tested, rolled back and replicated.

How: end-to-end pipeline and verification points

StageArtifactsVerificationWhat you see when it fails
① CommitServiceMonitor, PrometheusRule, Probe, dashboards, valuesPR review—
② CIbuild/*.rules.yml, dashboards/build/*.jsonpromtool check/test, jq, jsonnetfmt, terraform plan, kubeconform (including CRD schema)PR turns red
③ GitOpsCRs and ConfigMaps in the clusterServerSideApply, admission webhook, sync waveOutOfSync / Degraded, webhook rejection
④ Operatorprometheus.yaml.gz, rulefiles ConfigMapselector matching, object validityOperator logs; (silent) missing job
⑤ Prometheustargets, rule evaluationconfig-reloader,prometheus_config_last_reload_successfulPrometheusBadConfig, 0/0 up
⑥ AlertingAlertmanager notificationsWatchdog (dead man's switch), thresholds tested with promtoolNo notifications / alert storms
⑦ Visualization and probingGrafana dashboards, probe_successsidecar logs, provisioned marker, black-box alertsdashboard missing, ProbeFailed

When: self-assessed maturity

LevelCharacteristics
L1 Manualhelm install + build dashboards and alerts in the UI
L2 DeclarativeServiceMonitor / PrometheusRule / dashboard ConfigMaps in Git, applied manually
L3 GitOpsArgo CD / Flux reconciles; CRDs managed separately; UI read-only
L4 Testingrule unit tests, dashboard build and validation, Terraform plan in PRs
L5 Closed loopblack-box + white-box + SLO (Lesson 6); alerts include a runbook and dashboard links; regular drills
Common misconceptions① “Once it's code, it can't go wrong” — it moves errors earlier, into the PR, but silent failures such as selector mismatches still need absent() alerts as a safety net. ② “Cleanup just means deleting the namespace” — CRDs are cluster-scoped; deleting a CRD cascades and removes all CRs (including other teams' ServiceMonitors), so delete them last and with care. ③ “Lesson 6 requires reinstalling everything” — no: this lesson's kind cluster, kps, Argo CD and the monitoring-config repository all continue to be used.

End to end: monitoring-as-code pipeline

① Git PRmonitoring-config ② CIpromtool · jsonnet · tf plan ③ Argo CDSSA · wave ④ Operatorselector · generation ⑤ Prometheusreload · scrape ⑥ AlertmgrNotifications ⑦ Grafana (sidecar)Dashboard ConfigMap TerraformExternal / managed Grafana ⑦ blackbox Probeprobe_success → alerts / SLO Verification points: PR (tests) → sync (admission/SSA) → reconciliation (selector) → runtime (reload success, Watchdog, absent, ProbeFailed) Lesson 6: after ⑤, add a Thanos sidecar / remote_write and multi-cluster aggregation; Lesson 7: go deeper into ⑤'s TSDB, cardinality and performance
Figure 8-1 Every arrow has automated verification; silent failures are covered by absent / Watchdog

Resource list for this lesson (keep / can delete)

ResourceLocationNeeded for Lessons 6–7?
kind cluster labLocal DockerKeep
kps (release kps) + CRDsmonitoringKeep (Lesson 6 modifies the values to add Thanos)
myapp + ServiceMonitor + PrometheusRulemyappKeep (data source for the SLO and cardinality experiments)
blackbox + ProbemonitoringKeep (availability SLO)
Argo CD and the three ApplicationsargocdRecommended to keep
Grafana resources created by Terraform, service account tokenGrafanaCan delete (terraform destroy)
alert-sink echo servicemonitoringCan delete

Animation: end-to-end journey of one change

Scenario: add an alert to myapp MyappSlowRequests. Play it step by step, or pick a stage to inject a problem and see where it gets stopped.

After selecting, click “Play”.
$ # logs

Full-stack health check (one-page command)

#!/usr/bin/env bash
# Lesson 5 environment health check: any failure prints ✗
set -u
ok(){ printf '✓ %s\n' "$1"; } ; bad(){ printf '✗ %s\n' "$1"; }
P=localhost:9090
q(){ curl -s "$P/api/v1/query" --data-urlencode "query=$1" | jq -r '.data.result[0].value[1] // "none"'; }

kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus -o jsonpath='{.status.conditions[?(@.type=="Reconciled")].status}' | grep -q True && ok "Prometheus CR Reconciled" || bad "Prometheus CR not reconciled"
[ "$(q 'prometheus_config_last_reload_successful')" = "1" ] && ok "config reload succeeded" || bad "config reload failed"
[ "$(q 'count(up{namespace="myapp",job="myapp"} == 1)')" != "none" ] && ok "myapp targets UP" || bad "myapp has no UP targets"
[ "$(q 'count(ALERTS{alertname="Watchdog",alertstate="firing"})')" = "1" ] && ok "Watchdog firing (alert pipeline OK)" || bad "Watchdog not firing"
[ "$(q 'count(probe_success == 1)')" != "none" ] && ok "black-box probe succeeded" || bad "no successful probes"
kubectl get cm -A -l grafana_dashboard=1 -o name | grep -q myapp-red && ok "myapp dashboard ConfigMap exists" || bad "dashboard ConfigMap missing"
argocd app list -o name 2>/dev/null | while read a; do s=$(argocd app get "$a" -o json | jq -r '.status.sync.status + "/" + .status.health.status'); [ "$s" = "Synced/Healthy" ] && ok "$a $s" || bad "$a $s"; done
✓ Prometheus CR Reconciled
✓ config reload succeeded
✓ myapp targets UP
✓ Watchdog firing (alert pipeline OK)
✓ black-box probe succeeded
✓ myapp dashboard ConfigMap exists
✓ argocd/kps Synced/Healthy
✓ argocd/monitoring-config Synced/Healthy
✓ argocd/prometheus-operator-crds Synced/Healthy

Cleanup commands

A. Recommended: clean up only this lesson's temporary resources (keep for Lessons 6–7)

cd ~/promlab/monitoring-config/terraform/grafana && terraform destroy -auto-approve
curl -s -X DELETE -u admin:$PW localhost:3000/api/serviceaccounts/$SA_ID
kubectl -n monitoring delete pod,svc alert-sink --ignore-not-found
pkill -f 'kubectl.*port-forward' || true

B. Full cleanup (if you are not continuing with Lessons 6–7)

# 1) Stop GitOps first so it does not recreate the resources (non-cascading delete of the Application)
for a in monitoring-config kps prometheus-operator-crds; do
  kubectl -n argocd patch application $a --type json -p '[{"op":"remove","path":"/metadata/finalizers"}]' 2>/dev/null
  kubectl -n argocd delete application $a
done
# 2) Delete workloads and declarations
helm uninstall blackbox -n monitoring
helm uninstall kps -n monitoring 2>/dev/null || true      # the release may not exist if it was already migrated to Argo CD
kubectl delete ns myapp monitoring
# 3) Delete the CRDs last (this deletes ALL CRs of those kinds in the cluster!)
kubectl get crd -o name | grep monitoring.coreos.com | xargs kubectl delete
# 4) Or delete the whole kind cluster (most thorough)
kind delete cluster --name lab

Risk: Step 3 deletes every team's ServiceMonitors / PrometheusRules in the cluster; never run it on a shared cluster. How to verify:kubectl get crd | grep monitoring.coreos.com No output; kind get clusters the lab no longer appears in the list.

Goal: use the health check script to confirm the Lesson 5 environment is complete, and complete one “end-to-end change” as a self-test.
Run the health check: save the script from “Command” as chmod +x , then run it; for each ✗, use the troubleshooting tree below to locate the cause.
End-to-end change: in one PR: ① add a new alert MyappSlowRequests (P99 > 1s for 10m) to PrometheusRule; ② the matching promtool tests (positive + negative); ③ add a P99 panel to the Grafonnet dashboard and build it; ④ after merge, Argo CD syncs, the new alert appears on the Prometheus Rules page, and the Grafana panel updates. Record the time from merge to effect (Argo CD polling + kubelet volume sync + reload).
Failure drill: pick a scenario from the troubleshooting tree at random (for example, a wrong ServiceMonitor port name), have a peer locate it using only commands, and time it.
Cleanup: run cleanup A; do not run cleanup B (Lesson 6 continues).

Case 1: migration path from L1 to L4 (one quarter)

Weeks 1–2: Inventory all dashboards and alerts in the UI and export the JSON to Git; put kps values in Git and pin the version. Weeks 3–6: Argo CD takes over kps (releaseName unchanged) and the CRDs; dashboards become ConfigMaps, and the UI is read-only. Weeks 7–10: Migrate rules to PrometheusRule and fill in promtool tests; make CI checks required. Weeks 11–13: Black-box probes cover all public entry points; absent / Watchdog as a backstop; alerts include a runbook.

Case 2: the platform team's “monitoring onboarding contract”

Written into internal docs: ① ServiceMonitor/PodMonitor/PrometheusRule must carry release: kps; ② metric name prefix = service name, counters end with _total ; ③ every service has at least a RED dashboard, an availability alert and promtool tests; ④ dashboard uid = <team>-<service>-<topic>; ⑤ public entry points must have a Probe. Use admission policies (Kyverno / ValidatingAdmissionPolicy) to check ① automatically.

Case 3: managing expectations on change propagation delay

Typical delay from merge to effect: Argo CD polling (about 3 minutes by default; a webhook can shorten it) + Operator reconciliation (seconds) + kubelet sync of the Secret/ConfigMap volume (usually tens of seconds to a minute or two) + reload (seconds). Write “takes effect within 5 minutes of merge” in the team docs, so nobody makes a “quick manual fix” in the UI.

Interactive troubleshooting tree: all failure types in this lesson

Start from the symptom and choose step by step to get the diagnostic command and the fix.

Additional: three combined failures across modules

Everything looks synced, but the Rules page still shows the old alert

Cause: reload failed (an error in the new rules or new scrape config was rejected by Prometheus, so the old config keeps running); or kubelet has not yet synced the volume.

kubectl -n monitoring logs prometheus-kps-kube-prometheus-stack-prometheus-0 -c config-reloader --tail=20
kubectl -n monitoring logs prometheus-kps-kube-prometheus-stack-prometheus-0 -c prometheus | grep -i 'error loading\|reload' | tail
Argo CD shows Synced/Healthy, but the ServiceMonitor in the cluster differs from Git

Cause: Other tools (helm, another Argo CD Application, a ServiceMonitor shipped with the chart) also manage an object with the same name; or the ignoreDifferences scope is too broad.

kubectl -n myapp get smon myapp -o yaml | yq '.metadata.managedFields[].manager'
kubectl -n myapp get smon myapp -o jsonpath='{.metadata.labels.argocd\.argoproj\.io/instance}{"\n"}'
Watchdog alert is not firing

Cause: The default rule has been disabled (defaultRules.create: false or defaultRules.rules.general: false), the ruleSelector was changed, or Prometheus rule evaluation has failed overall. Watchdog not firing means the “alerting pipeline itself” has a problem, which is more serious than any business alert.

kubectl -n monitoring get promrule | grep general
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[] | select(.name=="general.rules") | .rules[].name'
Command-line exercises
1. One command to count: how many ServiceMonitor jobs does kps currently select (grouped by namespace)?
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip \
  | yq -r '.scrape_configs[].job_name' | grep '^serviceMonitor/' | cut -d/ -f2 | sort | uniq -c
2. List all currently firing alerts and their severity (without opening the UI).
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | select(.state=="firing") | [.labels.alertname, .labels.severity] | @tsv'
Scenario analysis
A new colleague asks: “We already have Argo CD, so why do we still need promtool tests, absent alerts and blackbox? Aren't they redundant?” Use this lesson's pipeline to explain what each layer guards against.

Argo CD only guarantees “cluster = Git”; it does not guarantee that what is in Git is correct. promtool guards against “rule logic errors” (at the PR stage); the admission webhook guards against “syntax errors entering the cluster”; absent alerts guard against “silent failures such as selector mismatches that leave no data”; Watchdog guards against “the alerting pipeline itself failing”; blackbox guards against “user-side failures that application metrics cannot see”. Each covers a different stage of the pipeline, and none replaces the others.

Verified teaching videos

▶
How Prometheus Monitoring works | Prometheus Architecture explained — TechWorld with Nana
English · Review of the Prometheus architecture (Lesson 1 content)
▶
Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1 — TechWorld with Nana
English · Review of kps and the Operator

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.

Shot 1 · 0–30s
Visual: icons for the five lessons line up along a timeline: instrumentation, alerting, Azure, AWS, codification, and finally they flow into one Git repository.
Narration: in the first five hours, we went from a single metrics endpoint to a whole monitoring stack that lives in Git.
Shot 2 · 30–65s
Visual: an alert change passes through the PR, CI, Argo CD, the Operator and Prometheus in turn; at each stop a checkpoint lights up green.
Narration: every stage has automated verification, and silent failures are covered by absent and Watchdog.
Shot 3 · 65–90s
Visual: the kind cluster icon is tagged “Keep”, and an arrow points to Thanos and multi-cluster in Lesson 6.
Narration: the environment is kept, and in the next hour we build long-term storage and SLOs on top of it.
or score ≥ 70% on the Quiz

Command cheat sheet

kps · Operator CRD · GitOps · Grafana as code · promtool · blackbox (release kps · namespaces monitoring / myapp)
Install and upgrade kps
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm upgrade --install kps prometheus-community/kube-prometheus-stack \
  -n monitoring --create-namespace --version 93.3.0 -f kps/values.yaml
helm show values prometheus-community/kube-prometheus-stack --version 93.3.0 > default-values.yaml
helm template kps prometheus-community/kube-prometheus-stack --version 93.3.0 -n monitoring -f kps/values.yaml --skip-crds
Operator troubleshooting trio
kubectl -n monitoring get prometheus kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.spec.serviceMonitorSelector}{"\n"}'
kubectl get smon,pmon,probe,promrule -A --show-labels
kubectl -n monitoring get secret prometheus-kps-kube-prometheus-stack-prometheus \
  -o jsonpath='{.data.prometheus\.yaml\.gz}' | base64 -d | gunzip | grep job_name
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator --tail=50
Prometheus API
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090:9090 &
curl -s 'localhost:9090/api/v1/targets?state=active' | jq -r '.data.activeTargets[] | [.scrapePool,.health] | @tsv'
curl -s localhost:9090/api/v1/rules | jq -r '.data.groups[].name'
curl -s localhost:9090/api/v1/alerts | jq -r '.data.alerts[] | .labels.alertname + " " + .state'
CRD upgrade
kubectl get crd prometheuses.monitoring.coreos.com \
  -o jsonpath='{.metadata.annotations.operator\.prometheus\.io/version}{"\n"}'
V=v0.95.2
for c in alertmanagerconfigs alertmanagers podmonitors probes prometheusagents prometheuses prometheusrules scrapeconfigs servicemonitors thanosrulers; do
  kubectl apply --server-side --force-conflicts -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/$V/example/prometheus-operator-crd/monitoring.coreos.com_$c.yaml
done
GitOps
argocd app diff kps && argocd app sync kps
argocd app get kps --show-operation
flux reconcile hr kps -n monitoring --with-source
flux get hr -n monitoring
# Required for Argo CD: syncOptions: [ServerSideApply=true]; helm.releaseName: kps
Grafana
kubectl -n monitoring get secret kps-grafana -o jsonpath='{.data.admin-password}' | base64 -d
kubectl get cm -A -l grafana_dashboard=1
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20
curl -s -u admin:$PW 'localhost:3000/api/search?query=myapp' | jq -r '.[].uid'
curl -s -X POST -u admin:$PW localhost:3000/api/admin/provisioning/dashboards/reload
Grafonnet + Terraform
jb install github.com/grafana/grafonnet/gen/grafonnet-latest@main
jsonnet -J vendor grafonnet/myapp-overview.jsonnet -o dashboards/build/myapp-overview.json
export GRAFANA_URL=http://localhost:3000 GRAFANA_AUTH=glsa_...
terraform -chdir=terraform/grafana init
terraform -chdir=terraform/grafana plan
promtool
yq '.spec' manifests/myapp/prometheusrule.yaml > build/myapp.rules.yml
promtool check rules --lint=all --lint-fatal build/*.rules.yml
promtool test rules rules/tests/*.test.yml
promtool test rules --run 'MyappDown' --diff rules/tests/myapp.test.yml
promtool test --junit=build/junit.xml rules rules/tests/*.test.yml
blackbox
helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter \
  -n monitoring --version 11.21.3 -f blackbox/values.yaml
kubectl -n monitoring port-forward svc/blackbox-prometheus-blackbox-exporter 9115:9115 &
curl -s 'localhost:9115/probe?target=http://myapp.myapp.svc:5000/healthz&module=http_healthz&debug=true'
curl -s localhost:9115/config
Series notation quick reference (promtool)
0+60x10      0 60 120 … 600 (11 points, rate = 1/s @ 1m interval)
1x5          1 1 1 1 1 1
10-2x3       10 8 6 4
1 _ 0        _ = missing sample (look back to the most recent value within 5m)
1 stale 0    stale = stale marker (no value immediately)
for: 2m      timing starts from the first time it is true; firing only when eval_time ≥ activeAt + 2m

Quick troubleshooting table

SymptomMost likely causeFirst command
My job is not in /targets at allServiceMonitor missing release: kpskubectl get smon -A -l 'release!=kps'
job exists but 0/0 upService labels / port name / namespaceSelector mismatchkubectl -n myapp get svc --show-labels
target DOWN 404Wrong path or portcurl -si localhost:5000/metrics
PrometheusRule apply rejectedPromQL syntax error (webhook)promtool check rules
Rule does not appear on the Rules pageMissing label / reload failedlogs … -c config-reloader
Argo CD: annotations Too longServerSideApply not enabledsyncOptions: [ServerSideApply=true]
After upgrade, the Operator reports CRD-related errorsCRD not upgradedCompare the CRD annotation version with appVersion
All ServiceMonitors lost after renamingreleaseName changedhelm.releaseName: kps
Dashboard does not loadlabel value is not "1" / JSON errorsidecar and grafana container logs
panel Datasource ${DS_PROMETHEUS} not foundExported in the “external sharing” formatchange the uid to prometheus
terraform plan always shows a diffJSON contains id/versionDelete these fields
probe scrape DOWN (deadline exceeded)module timeout ≥ scrape timeoutdebug=true

Recommended config snippets

Minimal ServiceMonitor template
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: <app>
  namespace: <ns>
  labels: {release: kps}
spec:
  selector:
    matchLabels: {app.kubernetes.io/name: <app>}
  endpoints:
    - port: http
      path: /metrics
      interval: 30s
Backstop alerts every service needs
- alert: <App>TargetMissing
  expr: absent(up{namespace="<ns>", job="<svc>"})
  for: 5m
  labels: {severity: critical}
- alert: <App>ProbeFailed
  expr: probe_success{service="<app>"} == 0
  for: 2m
  labels: {severity: critical}

Capstone lab + final quiz

Starting from a kind cluster with only myapp, turn the whole monitoring setup into a state where “everything is in Git and everything is tested”
After class ≈ 90 minutesNo cloud costsCovers 8 modules
Scenario You have taken over the team's kind cluster lab: myapp runs in the myapp namespace, the monitoring stack was installed by a colleague with “manual helm install”, the dashboards live in the UI, the alerts have no tests, and nobody knows when the certificates expire. Goal: without interrupting monitoring (Watchdog keeps firing, targets are not lost), move everything into the monitoring-config repository, reconciled by Argo CD, with tests in PRs, and add black-box probing.
Cost, permissions and security Everything is done locally. You need: admin rights on the kind cluster, a GitHub repository (Actions free tier), and Grafana Admin (only to create the Terraform service account; its token expires in 1 day). Do not commit Grafana passwords/tokens or webhook URLs to Git; delete the service account during cleanup.
Inventory (Module 1): helm get values kps -n monitoring Export the existing values to kps/values.yaml; record the chart version, CRD annotation version, number of targets and currently firing alerts as the pre-migration baseline.
helm list -n monitoring
curl -s 'localhost:9090/api/v1/targets?state=active' | jq '.data.activeTargets | length'
Monitoring declarations (Module 2): write a ServiceMonitor and PrometheusRule for myapp (including MyappTargetMissing, MyappDown, MyappHighErrorRate, MyappRedisDown, MyappHighLatencyP95 and two recording rules), all carrying release: kps; verify both Pods are up.
GitOps takeover (Module 3): create the three Argo CD Applications CRD / kps / monitoring-config (ServerSideApply, releaseName: kps, sync wave); diff first, then sync; confirm object names are unchanged, the Prometheus Pod did not recreate its PVC, and Watchdog keeps firing.
Dashboards as code (Modules 4, 5): publish the myapp RED dashboard as a ConfigMap (folder myapp); Grafonnet generates myapp-overview and deploys it with Terraform to the platform (terraform) folder; after editing it in the UI, use terraform plan to detect the drift.
Rule tests and CI (Module 6): every alert gets at least 1 positive and 1 negative test; GitHub Actions runs check (--lint=all --lint-fatal) + test (--junit) + jq empty + jsonnet build consistency + terraform validate; make it a required check. Submit a PR with a reversed threshold and confirm it is blocked.
Black-box probing (Module 7): install blackbox (managed by GitOps), and Probe covers myapp's internal /healthz and two external HTTPS sites; add ProbeFailed, ProbeSlow, TLSCertExpiringSoon and their promtool tests.
Failure drills (Modules 2, 7, 8): inject and then restore in turn: ① change the ServiceMonitor label to release: prometheus; ② break the Service selector; ③ delete the Grafana Pod (the dashboard should recover automatically). For each drill, record which alert fires first and which command you used to locate it.
Wrap-up (Module 8): run the health check script and get all ✓; terraform destroy; delete the service account; keep the cluster for Lesson 6.

Acceptance checklist

Open-ended self-test (answer first, then expand the reference answers)

1. Why is a “ServiceMonitor label mismatch” one of the most dangerous failure classes in the Operator model? Which two methods would you use to defend against it?

Because it produces no errors: the Operator silently ignores it, Prometheus has no such job,up the series simply does not exist, so the up == 0 alerts never fire. Defenses: ① at runtime, an absent(up{…}) alert; ② at commit time, use admission policies / CI to check that ServiceMonitors carry the agreed labels (or use a fixed selector in values that does not depend on the release).

2. Describe the steps from a PrometheusRule git push to appearing on the Rules page, and the possible delay at each step.

push → Argo CD polling/webhook (up to about 3 minutes) → server-side apply → admission webhook validates syntax → the Operator receives an informer event, selects by ruleSelector, and updates the rulefiles ConfigMap (seconds) → kubelet syncs the ConfigMap volume (tens of seconds to a minute or two) → config-reloader detects the file change and POSTs /-/reload (seconds) → the next evaluation cycle starts evaluating.

3. What is your checklist for a kps major version upgrade?

Read UPGRADE.md; in the same PR, upgrade the CRDs (separate chart or server-side apply) and kps; in CI, render the old and new versions and diff them, checking object names, selectors and default rule changes; extract the default PrometheusRules and run promtool check; sync in a non-production cluster first and watch Watchdog, the target count and the Operator logs; never auto-merge major upgrades.

4. When should you use sidecar ConfigMaps and when should you use Terraform to manage dashboards? Can you use both?

In-cluster Grafana with dashboards shipped alongside the app → ConfigMap; managed/external Grafana, or when you need to manage permissions / teams / service accounts → Terraform. They can coexist in the same Grafana, but a given uid can have only one owner; otherwise they overwrite each other.

5. Give an example of an error that only promtool tests can catch, which neither check rules nor the webhook can detect.

Changing sum by (namespace) to sum, is syntactically valid, but the alert loses its namespace label, so the namespace-based Alertmanager route breaks; or for a for that is too long causes short outages to be missed; or the threshold direction is reversed.

6. Why should blackbox alerts be based on probe_success rather than up? What blind spots does in-cluster probing have?

When a probe fails, /probe the exporter still returns successfully (up == 1), and the failure shows up in probe_success 0. An in-cluster prober shares fate with the system under test: during a whole-cluster failure or an egress network failure, the prober fails too, and it cannot see public DNS / CDN problems. Critical entry points need probes from outside the cluster, and you should use absent(probe_success) to monitor the prober itself.

Final quiz (12 questions, covering all modules)

Sources and version notes

Verification basis for the technical facts in this lesson (verified 2026-11-15)
TopicVerified findingsSource (accessed 2026-11-15)
kube-prometheus-stack93.3.0 (2026-11-13), appVersion v0.95.2, kubeVersion >=1.25; dependencies: crds, kube-state-metrics 9.0.1, prometheus-node-exporter 5.1.0, grafana 14.4.1 (oci://ghcr.io/grafana-community/helm-charts), prometheus-windows-exporter 0.14.0; default images Prometheus v3.16.0-distroless, Alertmanager v0.35.0, Thanos v0.42.5; *SelectorNilUsesHelmValues: true → selector release: {{ .Release.Name }}; fullname truncated to 26 characters; grafana sidecar dashboards label: grafana_dashboard,labelValue: "1",searchNamespace: ALL, datasources grafana_datasource/"1", default datasource uid prometheus; crds.upgradeJob is a preview feature and disabled by default; README: Argo CD requires ServerSideApply=true (the CRDs are about 840 KiB, over the 262144-byte annotation limit), does not include the blackbox exporter, and is distributed as both OCI and HTTP repositories; UPGRADE.md 92.x→93.x requires server-side apply for the CRDschart source (Chart.yaml, values.yaml, _helpers.tpl, README) · UPGRADE.md · Releases
prometheus-operator-crds chart33.0.2, appVersion v0.95.2chart
Prometheus Operatorv0.95.2 (released 2026-11-12, CHANGELOG dated 2026-11-10); v0.95.0 added extraScrapeMetrics, distroless images; the status subresource of config-type CRs requires StatusForConfigurationResources a feature gate; ScrapeConfig and AlertmanagerConfig are v1alpha1; the job name generated by ServiceMonitor serviceMonitor/<ns>/<name>/<i>; the default service discovery role is Endpoints (EndpointSlice can be set); rule file name <ns>-<name>-<uid>.yaml, ConfigMap …-rulefiles-N, label prometheus-name; config output /etc/prometheus/config_out/prometheus.env.yaml; CRD annotation operator.prometheus.io/version; short names smon, pmon, promrule; Probe fields jobName, prober, module, targets.staticConfig.staticCHANGELOG · API reference · v0.95.2 source (pkg/prometheus, pkg/operator, example/prometheus-operator-crd)
Prometheus / promtoolPrometheus v3.16.0 (2026-11-05); unit test format (rule_files, evaluation_interval, group_eval_order, fuzzy_compare, tests[].interval/input_series/alert_rule_test/promql_expr_test/external_labels/external_url/start_timestamp; series notation a+bxn, a-bxn, axn, _, stale); promtool test rules Parameters --run (regex, repeatable),--debug,--diff (experimental),--ignore-unknown-fields; --junit is test the command argument; check rules 's --lint (default duplicate-rules) and --lint-fatal (exit code 3)Unit testing for rules · v3.16.0 cmd/promtool/main.go · Releases
Alertmanager · node_exporterAlertmanager v0.35.0 (2026-11-09); node_exporter v1.12.1 (2026-07-14)each project's GitHub Releases
GrafanaGrafana v13.3.1 (2026-11-10, with 13.2.6 and 13.1.10 patches also available); grafana chart 14.4.1 appVersion 13.3.1; k8s-sidecar 2.14.3; alerting sidecar sidecar.alerts.enabled: false,label: grafana_alert; alert file provisioning format (groups / contactPoints / policies); file-provisioned resources are not editable in the UI; “as code” docs: Grafonnet is not officially supported, Grizzly has been removed, Foundation SDK / Grafana CLI recommended; Git Sync exists (status per official docs)Grafana Releases · grafana chart · alert provisioning · as code
Terraform grafana providerv4.55.0 (2026-11-13); provider parameters url / auth (environment variables supported); resource fields: grafana_dashboard (config_json, folder, overwrite, message), grafana_folder (uid, title, prevent_destroy_if_not_empty), grafana_contact_point (webhook block, disable_provenance), grafana_notification_policy (contact_point, group_by, policy/matcher), grafana_rule_group (folder_uid, interval_seconds, rule/data, disable_provenance), grafana_service_account(_token)Registry docs · Releases
Grafonnetno release tags; grafonnet-latest currently points to grafonnet-v13.0.0; the README marks it experimental; install with jb install github.com/grafana/grafonnet/gen/grafonnet-latest@main, go-jsonnet recommended; util.grid.makeGrid forces uniform sizes,wrapPanels keeps panel sizesgrafana/grafonnet(README, gen/…/custom/util/grid.libsonnet)
blackbox exporterblackbox_exporter v0.29.1 (2026-10-21); prometheus-blackbox-exporter chart 11.21.3 (appVersion v0.29.1), default module http_2xxblackbox_exporter · chart · multi-target exporter guide
GitOps toolsArgo CD v3.6.1 (2026-11-04); Flux v2.10.0 (2026-10-26); Argo CD sync options ServerSideApply=true,SkipDryRunOnMissingResource=true; Flux HelmRelease install/upgrade.crds supports CreateReplaceArgo CD Sync Options · Flux HelmReleases
CI action versionsactions/checkout v7.0.1; actions/upload-artifact v7.0.2GitHub Releases (queried via API)
Facts carried over from prerequisite courseskind v0.33.0 / Kubernetes 1.37, Helm 4.3.x, Terraform 1.17.xSee K8s course,Helm course source page

Video verification notes

All videos below were verified for title and channel via the YouTube oEmbed API (2026-11-15): TechWorld with Nana “Setup Prometheus Monitoring on Kubernetes using Helm and Prometheus Operator | Part 1” (QoDqxm7ybLc), “Prometheus Monitoring - Steps to monitor third-party apps using Prometheus Exporter | Part 2” (mLPg49b33sA), “How Prometheus Monitoring works | Prometheus Architecture explained” (h4Sl21AKiDg), “What is GitOps, How GitOps works and Why it's so useful” (f5EpcWp0THw), “ArgoCD Tutorial for Beginners | GitOps CD for Kubernetes” (MeU5_k9ssrs); That DevOps Guy “Introduction to the Prometheus Operator on Kubernetes” (LQpmeb7idt8), “Prometheus Operator in Kubernetes Explained” (qMKSBUkSRYc); Anton Putra “Prometheus Operator Kubernetes Tutorial: ServiceMonitor - PodMonitor - Step-by-Step” (HOmdYtsB950); DevOps & AI Toolkit “Flux CD v2 With GitOps Toolkit - Kubernetes Deployment And Sync Mechanism” (R6OeIgb7lUI); Grafana “Grafana 12 TL;DR: Observability as Code, Dynamic Dashboards & More Explained in 7 Min” (mHSzaVYBh38), “Git Sync: Observability as code built for scale | Demo” (gjhmarpMPCY), “Part 1: Observability as Code with Grafana Foundation SDK | Grafana 12” (_OKQoABmg0Q), “How To Manage Checks With Terraform | Grafana Cloud Synthetic Monitoring” (6DlLuuNcFqA); Sebastian Thomas “Grafana dashboards as code demo” (xEi-UKYCIYI); Let's Learn Devops “Grafana Provider in Terraform | #1” (ht18nXq4HMo); Azure Terraformer “Mixing Azure And Grafana In A Terraform Provider Mashup!” (u8FlE3KYztY); CNCF “Lightning Talk: Prometheus rules validation one step further - Martin Chodur, Seznam” (YYSJ--KhlIo); DevOps Simplified “Prometheus Alerting Rules for Beginners: Pending, Firing and promtool Tests (Real Output)” (Op0cUlooq4k); Bhoopesh Sharma “Monitoring Websites with Blackbox Exporter Prometheus | Prometheus Synthetic Monitoring | Helm” (O4pKFUE8FDg); House of Logic blog “How to Configure the Prometheus Blackbox Exporter” (58LKuEhfF6E). oEmbed does not return duration or publish date, so durations are not listed. The three topics “GitOps management of kps and CRD upgrades”, “kps sidecar loading dashboards” and “Grafonnet” have no verified dedicated video, so storyboard scripts are provided instead. All videos are in English, and most were recorded before the versions used in this lesson, so the lesson's details take precedence.

Voice narration notes

The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud, with English terms pronounced in en-US; the result depends on the operating system's voice packs. This courseware has no embedded audio (MP3 cannot be generated); the narration script can be passed to a TTS tool to produce audio.

Known limitations

  • The commands, YAML, HCL and Jsonnet in this lesson are written from official docs and source code,but have not actually been run in this environment (including the promtool unit test files — their timing and extrapolation were checked by hand); the Pod names, IPs, times, remaining certificate days and log wording in the “expected output” are all example values.
  • Points handled conservatively and marked “refer to official docs”: Grafana Git Sync feature status and supported providers; grafanactl maturity (v0.1.x); Terraform import ID format under multiple orgs; write-only/ephemeral handling of secrets in state; the exact wording of promtool failure output and blackbox debug logs; whether kps default rules are all omitted once control-plane components are turned off (if they still appear, you can use defaultRules.disabled to turn them off); whether an Argo CD webhook caBundle drift appears depends on version and configuration; this lesson only offers an optional ignoreDifferences.
  • The series outline says “Grafana 12”, but the latest version at verification time was 13.3.1, so this lesson is written for 13.3.1; the provisioning, sidecar and Terraform resources used here also exist in 12.x.
  • The kps Grafana sub-chart now comes from grafana-community/helm-charts (OCI); the old documentation's grafana/helm-charts links are for reference only.
  • The alert-sink in the lab uses a community echo image, for lab use only; the Grafana-managed alert example only demonstrates the format, and in production you choose between it and PrometheusRule.
  • The timing, counts and logs in the animations are illustrative of the mechanism (for example, kubelet volume sync delay uses typical values), and some retries and events are omitted.
  • Lessons 6–8 were written in parallel with this lesson; cross-lesson references should follow each lesson's final content.