Prometheus & Grafana Hour 5: Automated Operations — Operator, GitOps and Monitoring as Code
- Explain the reconciliation mechanism of the Prometheus Operator: it watches
Prometheus,ServiceMonitor,PodMonitor,Probe,ScrapeConfig,PrometheusRuleand other CRDs, and selects objects by label selector matching, and generatesprometheus.yaml.gza 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
labin themonitoringnamespace, install the releasekps, and for the namespacemyappin the myapp (port 5000), write a ServiceMonitor and PrometheusRule with therelease: kpslabel. - 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,releaseNameand the linkage with the selector. - Turn Grafana into code: the kps sidecar (
grafana_dashboard: "1",grafana_datasource: "1", optionalgrafana_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 rulesto write unit tests for alerts (input_seriesnotation,alert_rule_test,promql_expr_test,--junit). - Use blackbox exporter +
ProbeCRDs for HTTP / TLS synthetic probing, and understand/probe?target=&module=’s multi-target exporter pattern and relabeling, and writeprobe_successand certificate-expiry alerts.
Hour 1 time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (kind cluster lab · namespaces monitoring / myapp) |
|---|---|---|---|---|---|
| 0 | Before class | Preparation: kind cluster and Helm | Reuse 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 skeleton | Environment self-check list | Deploy myapp to namespace myapp |
| 1 | 00–06 | kube-prometheus-stack and Prometheus Operator | chart composition, 10 CRDs, Operator pattern, control-plane targets on kind, generated object names | The Operator expands the Prometheus CR into a StatefulSet / Secret / Service | helm upgrade --install kps |
| 2 | 06–13 | ServiceMonitor, PodMonitor and PrometheusRule | selector chain (Prometheus → ServiceMonitor → Service → EndpointSlice/Endpoints → Pod), named ports, PrometheusRule and admission webhook, ScrapeConfig | Core animation: Operator reconciliation (including fault injection such as “label mismatch”) | myapp ServiceMonitor + rules |
| 3 | 13–21 | Managing the monitoring stack with Helm and GitOps | values layering, version pinning, CRD upgrades, Argo CD ServerSideApply, Flux crds policy, releaseName pitfalls | GitOps sync simulator (Argo CD / Flux × 3 scenarios) | Argo CD manages kps and monitoring-config |
| 4 | 21–28 | Grafana provisioning | file provisioning vs sidecar, data source uid, dashboard ConfigMap, folder annotation, alert/contact point provisioning, UI read-only | the sidecar loading dashboards process (failures can be injected) | myapp RED dashboard ConfigMap |
| 5 | 28–35 | Terraform Grafana provider and Grafonnet | provider authentication (service account token), folder/dashboard/contact_point/notification_policy/rule_group, Grafonnet and Foundation SDK | Terraform plan drift simulation | jsonnet generates dashboard → terraform apply |
| 6 | 35–42 | Rule testing: promtool and CI | check rules, test rules, series notation, eval_time, for and pending, GitHub Actions | Alert unit-test timeline (drag eval_time) | Write tests for MyappDown / high error rate |
| 7 | 42–50 | Black-box monitoring: blackbox exporter | multi-target exporter pattern, modules, Probe CRD, relabel, probe_success, certificate expiry | Phase breakdown of one probe (DNS / connection / TLS / HTTP) | Install blackbox + Probe + alerts |
| 8 | 50–60 | Recap, self-test and cleanup for the first five hours | Knowledge 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 tree | Cleanup / keep |
| — | After class | Cheat sheet · Comprehensive lab | From an empty cluster to a monitoring stack “all in Git” | Final quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Install and understand kube-prometheus-stack | ✓ | · | ✓ | · | · | · | · | ✓ | helm upgrade --install kps | M1 lab |
| Operator reconciliation and selector troubleshooting | ✓ | ✓ | ✓ | · | · | · | ✓ | ✓ | kubectl get prometheus -o yaml | M2 lab |
| ServiceMonitor / PodMonitor / Probe | · | ✓ | · | · | · | · | ✓ | ✓ | kubectl get servicemonitor -A | myapp, blackbox |
| PrometheusRule and rule validation | · | ✓ | · | · | · | ✓ | ✓ | ✓ | promtool check rules | myapp-rules |
| GitOps management of the monitoring stack and CRD upgrades | · | · | ✓ | ✓ | · | · | · | ✓ | argocd app sync,flux reconcile hr | M3 lab |
| Grafana provisioning (sidecar / files) | · | · | · | ✓ | ✓ | · | · | ✓ | kubectl logs -c grafana-sc-dashboard | RED dashboard |
| Terraform / Grafonnet managing Grafana | · | · | · | ✓ | ✓ | · | · | ✓ | jsonnet -J vendor,terraform plan | M5 lab |
| Rule unit tests and CI | · | ✓ | ✓ | · | · | ✓ | · | ✓ | promtool test rules | GitHub Actions |
| Black-box / synthetic probing | · | · | · | · | · | ✓ | ✓ | ✓ | curl …/probe?debug=true | Probe + alerts |
What this course does not cover (and where to learn it)
| Topic | Why it is not in this course | Where to learn |
|---|---|---|
| Installation of Argo CD / Flux, detailed Application / HelmRelease fields, hooks and sync waves, remediation | Lesson 5 of the Helm course covers this systematically; this course only covers what is special about the “monitoring stack” chart | Helm course lesson 5 (module 4 Argo CD, module 5 Flux) |
Helm chart structure, values merging,helm upgrade parameters | Helm course topics | Helm 8 hours |
| kind cluster creation, Service / EndpointSlice / label selector basics, RBAC | K8s course topics | Kubernetes 8 hours |
| PromQL, alerting rule syntax, Alertmanager routing | Topics from lessons 1 and 2 (used directly in this course) | Lesson 1 · Lesson 2 |
| Managed Prometheus / Grafana (Azure, AWS) | Topics from lessons 3 and 4 | Lesson 3 · Lesson 4 |
| Thanos / Mimir long-term storage, multi-cluster, SLO burn rate | Lesson 6 topics (reuse this course's kind environment) | Lesson 6 |
| Cardinality, TSDB, performance tuning | Lesson 7 topics | Lesson 7 |
| Grafana Operator, Crossplane, Terraform resources for Grafana Cloud | Time constraints; mentioned only in comparison tables | Grafana “as code” documentation |
How to use this courseware
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).
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).
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.
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)
- Complete this course Lesson 1 and Lesson 2: locally, the myapp in
~/promlabhas already usedprometheus_clientto expose/metrics(gunicorn multiprocess mode usesPROMETHEUS_MULTIPROC_DIR), the imagemyapp:1.1has been built; you have writtenprometheus/rules/*.ymlalerting 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
| Resource | Cost | Permissions / risks |
|---|---|---|
| kind cluster lab + kube-prometheus-stack | Local, no cost | kps 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-config | Public 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.
Module 1 · kube-prometheus-stack and Prometheus Operator
- 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…).
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.
| Component | Created by | Role | Name in lab (release = kps) |
|---|---|---|---|
| Prometheus Operator | chart (Deployment) | watches CRDs and reconciles | kps-kube-prometheus-stack-operator |
| Prometheus | chart creates Prometheus CR → Operator creates StatefulSet | scraping, storage, rule evaluation | CR kps-kube-prometheus-stack-prometheus; Pod prometheus-kps-kube-prometheus-stack-prometheus-0 |
| Alertmanager | chart creates Alertmanager CR → Operator creates StatefulSet | grouping, inhibition, notification | Pod alertmanager-kps-kube-prometheus-stack-alertmanager-0 |
| Grafana | subchart grafana 14.4.1 (Deployment) | visualization; sidecar loads dashboards / data sources | kps-grafana (Service port 80) |
| kube-state-metrics | subchart | converts K8s object state into metrics (kube_pod_status_phase …) | kps-kube-state-metrics |
| node-exporter | subchart (DaemonSet) | node CPU / memory / disk / network | kps-prometheus-node-exporter |
| default rules and dashboards | chart (PrometheusRule, ConfigMap) | about 30 groups of kubernetes-mixin alerting and recording rules, dozens of dashboards | kps-kube-prometheus-stack-* |
| ServiceMonitor (self-monitoring and K8s components) | chart | scrapes apiserver, kubelet/cAdvisor, coredns, and the above components themselves | kubectl 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
- The Operator uses informers watch to watch all related CRs as well as Namespaces, Secrets, ConfigMaps and so on.
- Any change triggers a
PrometheusCR's reconciliation loop.: it selects configuration objects based on itsserviceMonitorSelector/serviceMonitorNamespaceSelectorand similar selectors. - Translate the selected objects into native Prometheus
scrape_configs(one job per endpoint, named likeserviceMonitor/myapp/myapp/0), gzipped and written to Secretprometheus-<CR name>'sprometheus.yaml.gzkey; rules are written to ConfigMapprometheus-<CR name>-rulefiles-N. - Ensure the StatefulSet exists with the correct spec (image, arguments, volumes, sidecars
config-reloader). - 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.yamlandPOST /-/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
| Option | Suitable for | Not suitable / notes |
|---|---|---|
| kube-prometheus-stack (this course) | The de facto standard for self-managed K8s cluster monitoring; needs declarative CRD management, default rules and dashboards | Many components, high resource usage; major-version upgrades require manual CRD handling (module 3) |
| prometheus-community/prometheus chart | Do not want an Operator; use prometheus.yml + annotation-based discovery | No ServiceMonitor; scraping and rules all live in one ConfigMap |
| kube-prometheus (jsonnet) | Needs deep customization and generates all manifests with jsonnet | Requires mastering jsonnet; disconnected from the Helm ecosystem |
| Only install prometheus-operator (bundle.yaml) | Only the CRDs and the Operator; you write the Prometheus CR yourself | No 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 |
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
Expanded view: what objects one Prometheus CR becomes
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts | Add the traditional HTTP repository | OCI 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.0 | Export 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.yaml | Install / upgrade | The release name determines all object names and selector labels release: kps |
kubectl get crd | grep monitoring.coreos.com | Confirm the 10 CRDs | CRDs remain after the chart is uninstalled |
kubectl -n monitoring get prometheus,alertmanager | List workload-type CRs | Shows VERSION / DESIRED / READY / RECONCILED / AVAILABLE |
kubectl -n monitoring logs deploy/kps-kube-prometheus-stack-operator | Operator logs | Selector 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).
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
/0 is kubelet itself,/1 is cAdvisor).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).
Watchdog is firing (it is a “dead man's switch” that always fires and is used to verify that the alert pipeline works).http://localhost:9090/targets all UP; in Grafana the “Kubernetes / Compute Resources / Cluster” dashboard shows data.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>'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).
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
Official documentation
Video storyboard script (about 70 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
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.
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.
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.
Module 2 · ServiceMonitor, PodMonitor and PrometheusRule
- Write a ServiceMonitor for myapp (
release: kps, named portshttp, 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.
What: four kinds of “scrape configuration” CRDs
| CRD | Selects | Generated SD | Typical use |
|---|---|---|---|
| ServiceMonitor | Labelled 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 |
| PodMonitor | Labelled Pod (no Service needed) | role pod | Jobs / DaemonSet sidecars without a Service, ports used only for metrics |
| Probe | A static URL or Ingress, probed through the prober (blackbox exporter) | static / ingress SD + relabel to /probe | black-box probing (module 7) |
| ScrapeConfig (v1alpha1) | Almost any Prometheus SD: static, file, http, DNS, consul, EC2, Azure … | Close to native configuration | Targets 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 whom | Field | myapp's value | Symptom when mismatched |
|---|---|---|---|---|
| ① | Prometheus CR → namespace of ServiceMonitor | serviceMonitorNamespaceSelector | {} = all namespaces | job does not appear in configuration |
| ② | Prometheus CR → ServiceMonitor labels | serviceMonitorSelector | release: kps | job does not appear in configuration (most common) |
| ③ | ServiceMonitor → namespace of Service | spec.namespaceSelector | matchNames: [myapp] (if omitted = the ServiceMonitor's own namespace) | job exists, target 0/0 |
| ④ | ServiceMonitor → Service labels | spec.selector | app.kubernetes.io/name: myapp (labels on Service , not on the Pod) | job exists, target 0/0 |
| ⑤ | endpoint → Service port | endpoints[].port (port name) or targetPort | http | job exists, target 0/0 |
| ⑥ | Service → Pod | Service spec.selector and readiness status | When a Pod is not ready, its address goes into notReadyAddresses | target 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 therelease: kpslabel to it — usuallyserviceMonitor.additionalLabelsorlabels). - 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).
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
Data flow: PrometheusRule from apply to effective
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl get servicemonitor,podmonitor,probe,prometheusrule -A | List all monitoring declarations | short name smon,pmon,promrule |
kubectl get smon -A -l release=kps | list only the ones kps will select | Compare with the CR's selector |
kubectl -n myapp get svc myapp --show-labels | Check ④ | the labels the ServiceMonitor selects by |
kubectl -n myapp get endpointslices -l kubernetes.io/service-name=myapp -o wide | Check ⑤⑥ | port name and ready addresses |
curl -s localhost:9090/api/v1/targets?state=active | jq … | Query targets via the API | more suitable for scripting than the UI |
curl -s localhost:9090/api/v1/rules | jq … | Confirm the rules are loaded | filter 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
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
# ① 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
0kubectl apply -f manifests/myapp/servicemonitor.yaml (release: kps); after about 1–2 minutes the target appears and both Pods are up.port: http to port: metrics, confirm that /targets shows serviceMonitor/myapp/myapp/0 (0/0 up), then change it back.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
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
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 + " " + .'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
Official documentation
- Getting started (ServiceMonitor example)
- Troubleshooting (target does not appear)
- Alerting / PrometheusRule
- ScrapeConfig CRD
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
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.
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.
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.
Module 3 · Managing the monitoring stack with Helm and GitOps
- 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, Fluxcrds: CreateReplace). - Write the Argo CD Application that manages kps (multi-source
$values,ServerSideApply=true,releaseName: kps) and the key fields of the Flux HelmRelease.
What: the three layers of “monitoring as code”
| Layer | Contents | Change frequency | Owner | GitOps object |
|---|---|---|---|---|
| L0 CRD | 10 monitoring.coreos.com CRDs | follows the Operator version | Platform | Separate Application / HelmRelease (synced first) |
| L1 monitoring stack | kps chart + values (Prometheus resources, retention, Alertmanager configuration, Grafana settings) | Monthly | Platform | Application kps / HelmRelease kps |
| L2 monitoring declarations | ServiceMonitor, PodMonitor, Probe, PrometheusRule, dashboard ConfigMap | Daily | Application teams | Alongside 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 editthe 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
- CRDs are too large:
crd-prometheuses.yamlabout 840 KiB, which exceeds the client-side applylast-applied-configurationannotation limit of 262144 bytes, which producesmetadata.annotations: Too long. The chart README explicitly requires Argo CD to useServerSideApply=true. - 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 thekubectl apply --server-sidenew CRDs first. The four GitOps approaches are summarized in the table below. - releaseName determines the selector: the template writes
release: {{ .Release.Name }}. In Argo CD,helm.releaseNameif not set, it equals the Application name; in Flux,releaseNameif not set, it is[<targetNamespace>-]<HelmRelease name>. If the Application is namedmonitoring, the selector becomesrelease: monitoring, and allrelease: kpsServiceMonitors instantly “lose contact”, and every object name changes as well. - 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
caBundlekeeps showing OutOfSync; for that field you canignoreDifferences, or switch toprometheusOperator.admissionWebhooks.certManager.enabled=true.
| CRD upgrade method | Approach | Pros | Notes |
|---|---|---|---|
| A. Manual / CI steps | Run per UPGRADE.md before upgrading kubectl apply --server-side (the 10 CRD files under the Operator release tag) | Matches official docs | Not 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: false | CRDs have their own version and audit trail; synced before kps | The Operator versions of the two charts must match (kps appVersion = CRD chart appVersion) |
C. crds.upgradeJob.enabled: true | kps uses a hook Job to server-side apply the CRDs before upgrading | Single chart | chart annotation marks it as preview feature, disabled by default; the Job needs RBAC and a pullable image |
D. Flux install/upgrade.crds: CreateReplace | helm-controller handles the crds/ directory | Simplest for Flux users | Flux 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.
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
Upgrade flow: one kps major version upgrade
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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
helm template kps prometheus-community/kube-prometheus-stack --version 93.3.0 -n monitoring -f kps/values.yaml | Local rendering | Diff against the old version's rendered output in the PR |
argocd app diff kps / argocd app sync kps | View diff / sync | Check whether SSA takes effect on first sync |
argocd app get kps --show-operation | Sync result and hook status | Failed resources and messages |
flux reconcile hr kps -n monitoring --with-source | Reconcile immediately | Flux version |
flux get hr -n monitoring | Ready / message | Failure reason |
kubectl get crd prometheuses.monitoring.coreos.com -o jsonpath='{.metadata.annotations.operator\.prometheus\.io/version}' | Operator version of the CRDs | Compare 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.
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.cd ~/promlab/monitoring-config git add . && git commit -m "chore: kps values, myapp monitoring" && gh repo create monitoring-config --public --source . --push
<GH_USER> then apply, and wait until everything is Synced / Healthy.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
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.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.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).
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
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
No verified dedicated video was found for “managing kube-prometheus-stack and its CRD upgrades with GitOps”; see the storyboard script below.
Official documentation
- kps UPGRADE.md
- Argo CD Sync Options
- Flux HelmRelease (crds policy)
- Helm lesson 5: Argo CD and Flux managing Helm
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
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.
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.
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.
Module 4 · Grafana provisioning: data sources, dashboards and alerts as code
- 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
uidand data sourceuid: prometheus; define contact points and notification policies with provisioning.
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.
| Resource | Docker Compose (lesson 1) | How kps does it | Default |
|---|---|---|---|
| Data sources | provisioning/datasources/prometheus.yaml | kps 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 with | enabled |
| Dashboards | provider YAML + JSON directory | with grafana_dashboard: "1" a ConfigMap; the sidecar writes it to /tmp/dashboards, and the chart's built-in provider reads from it | enabled,searchNamespace: ALL |
| Alerting resources | provisioning/alerting/*.yaml | grafana.sidecar.alerts.enabled: true after, with grafana_alert labelled ConfigMaps are loaded | disabled |
| Grafana settings | grafana.ini / environment variables | grafana."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
- In the Grafana Pod, the
grafana-sc-dashboardcontainer (kiwigrid/k8s-sidecar) uses the Kubernetes API to watch watch all namespaces (kps setssearchNamespace: ALL, so the chart creates a ClusterRole), for objects carrying thegrafana_dashboard=1label: ConfigMaps / Secrets. - each data key is written as a file into the shared emptyDir
/tmp/dashboards; iffolderAnnotation: grafana_folderis set, it writes to/tmp/dashboards/<annotation value>/. - Grafana's built-in sidecar dashboard provider (
foldersFromFilesStructure: truewhen 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. - the data source sidecar writes
/etc/grafana/provisioning/datasourcesand then callsPOST /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)
| Need | Recommendation | Reason |
|---|---|---|
| Dashboards shipped with the application (the app chart includes a ConfigMap) | sidecar ConfigMap | Same 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 permissions | Terraform | provisioning does not cover RBAC resources |
| Alert rules | Prefer Prometheus rules (PrometheusRule, module 2); for Grafana-managed alerts use provisioning or Terraform | Prometheus 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 PR | Grafana Git Sync (see Grafana “as code” docs; feature status per official documentation) | Not covered in this lesson |
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
Decision diagram: where a dashboard comes from
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
kubectl get cm -A -l grafana_dashboard=1 | List all dashboards that will be loaded | kps ships with dozens |
kubectl -n monitoring logs deploy/kps-grafana -c grafana-sc-dashboard --tail=20 | sidecar logs | Check whether files were written |
kubectl -n monitoring exec deploy/kps-grafana -c grafana -- ls -R /tmp/dashboards | Check the shared volume contents | Check whether the folder annotation takes effect |
curl -s -u admin:$PW 'localhost:3000/api/search?query=myapp' | Grafana API search | Confirm uid and folder |
curl -s -u admin:$PW localhost:3000/api/dashboards/uid/myapp-red | jq .meta.provisioned | Whether it is provisioned | true means the UI cannot save |
curl -X POST -u admin:$PW localhost:3000/api/admin/provisioning/dashboards/reload | Rescan immediately | alerting / 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
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
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; doneOpen Grafana → Dashboards → myapp → “myapp / RED”; all three panels should have data.
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"
}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' | taillogger=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'
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 -dNo 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
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
No verified dedicated video was found for “kps sidecar loads dashboard ConfigMap”; see the storyboard script below.
Official documentation
- Grafana Provisioning
- Alerting resource file provisioning
- grafana chart (sidecar parameters)
- kiwigrid/k8s-sidecar
Video storyboard script (about 70 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
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.
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.
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.
Module 5 · Terraform Grafana provider and Grafonnet
- Configure the provider with a service account token, and manage
grafana_folder,grafana_dashboard,grafana_contact_point,grafana_notification_policy, andgrafana_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→ Terraformfile()read it; know that Grafana officially prefers the Foundation SDK.
init/plan/apply, variables, state) — for systematic study see Terraform 8 hours; module 4. Importance:★★★★☆What: two tools, each handling one part
| Tool | Input | Output | Problem solved |
|---|---|---|---|
| Grafonnet | Jsonnet code (functions, variables, loops) | dashboard JSON | Hand-written JSON is verbose, copy-pasted and hard to reuse (e.g. RED panels for 20 services) |
| Foundation SDK | Go / TypeScript / Python / Java / PHP code | dashboard JSON (and other resources) | Same as above; the alternative Grafana recommends (Grafana docs note Grafonnet is not officially supported) |
| Terraform grafana provider | HCL + JSON | Real 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
- Authentication:
authSupports 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. - Dashboards:
config_jsonis 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 nextplanwill show aconfig_jsondiff → drift is detected and reverted atapplytime. Dashboards created via the API can be saved in the UI (unlike provisioned ones), which is both flexibility and a source of drift. - 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). - Notification policies:
grafana_notification_policyThey manage the entire policy tree (one per org); module 4's file provisioningpoliciesis mutually exclusive with it.
When: decision matrix
| Scenario | Recommendation |
|---|---|
| In-cluster Grafana, dashboards shipped with applications | ConfigMap + sidecar (module 4) |
| Managed / external Grafana; need permissions, teams, service accounts | Terraform provider |
| Kubernetes-native; want to manage Grafana with CRs | Grafana Operator (not covered in this lesson) |
| Many similar dashboards | Generate JSON with Grafonnet or the Foundation SDK, then deploy via any of the above |
| Push / pull resources from the command line | Grafana CLI (grafanactl, v0.1.x); Grafana docs mark Grizzly as “removed and no longer supported” |
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
Ownership: three kinds of resources in the same Grafana
| Source | Saveable in UI | How drift is detected | Example in this lesson |
|---|---|---|---|
| File provisioning / sidecar | Dashboards: no (allowUiUpdates: false); alerting resources: no | No drift (restored on every scan) | myapp-red (module 4) |
| Terraform (API) | Dashboards: yes; alerting resources: no (unless disable_provenance) | terraform plan | myapp-overview,oncall-webhook |
| Manual UI | Yes | None | Exploration 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.
Core commands
| Command | Purpose | Notes |
|---|---|---|
jb init && jb install github.com/grafana/grafonnet/gen/grafonnet-latest@main | Install Grafonnet into vendor/ | Generates jsonnetfile.json / jsonnetfile.lock.json, pinning the commit |
jsonnet -J vendor grafonnet/myapp-overview.jsonnet -o dashboards/build/myapp-overview.json | Generate JSON | go-jsonnet recommended (the C implementation has performance issues) |
jsonnetfmt --test grafonnet/*.jsonnet | Format check | Use in CI |
terraform init / plan / apply | Deploy | GRAFANA_URL,GRAFANA_AUTH environment variables |
terraform import grafana_dashboard.x <uid> | Take over existing resources | or 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.
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.
terraform plan the second run shows No changes..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.plan shows only the config_json change → apply.jsonnetfmt --test, build the JSON and git diff --exit-code dashboards/build (ensure build output is committed),terraform fmt -check,terraform validate.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.
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/buildThe 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
No verified dedicated video was found for Grafonnet; see the storyboard script below.
Official documentation
- Terraform Registry: grafana/grafana
- Grafana docs: Terraform
- Grafonnet docs · grafana/grafonnet
- Foundation SDK
Video storyboard script (about 75 seconds)
This courseware cannot directly generate video/MP3; a storyboard and narration script are provided.
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.
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.
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.
Module 6 · Rule testing: promtool and CI
- Write promtool test files:
rule_files,evaluation_interval,tests[].input_series(a+bxn,axn,_,stale),alert_rule_test,promql_expr_test. - Accurately work out
forandeval_timerelationship (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.
rate() and extrapolation; lesson 2's alert lifecycle. Importance:★★★★★What: promtool's three rule-related subcommands
| Command | What it checks | What 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 moment | real data distribution, scrape issues |
promtool check config | Full 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 notation | Expansion | Purpose |
|---|---|---|
0+60x10 | 0 60 120 … 600 (11 points in total) | Steadily increasing counter (+60 per minute → rate = 1/s) |
1x5 | 1 1 1 1 1 1 (a+0xn is shorthand, n+1 points) | Constant gauge |
10-2x3 | 10 8 6 4 | Decreasing |
1 1 _ _ 0 | _ = no sample at that moment (scrape failed) | Verify lookback behavior |
1 1 stale 0 | stale = 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:
fortoo long, which causes brief failures to be ignored,sumdrops thenamespacelabel 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)
- Sample time: the k-th value is at
start_timestamp + k × interval(starts from 0 by default; with a 1m interval → 0m, 1m, 2m …). - Rules are evaluated at every
evaluation_intervalevaluation; ateval_timethe assertion time, promtool has evaluated in order up to that moment. - The evaluation moment when the alert expression is first true is recorded as activeAt, state pending; when
eval_time − activeAt ≥ foris reached, it is firing; if the expression is false (or has no result) midway, it resets. - Example:
up=1 1 1 0 0 0 0,for: 2m→ true from 3m (pending),5m fires from; at the 4m assertion, writeexp_alerts: [](pending does not count as firing). - The lookback window of an instant selector defaults to 5m:
_(when the sample is missing), it takes the most recent value within 5 minutes;staleotherwise it immediately yields “no value”. exp_labelsYou must write out the alert's complete labels (excluding alertname) andexp_annotationswrite 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,PrometheusBadConfigand 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”.
.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)
Pipeline: rule checks in the PR
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
yq '.spec' manifests/myapp/prometheusrule.yaml > build/myapp.rules.yml | CRD → native rule file | Multi-document YAML with yq ea |
promtool check rules build/*.rules.yml | Syntax + lint | --lint=all --lint-fatal Stricter |
promtool test rules rules/tests/*.test.yml | Unit tests | Run multiple files at once |
promtool test rules --run 'MyappDown' … | Run only matching test groups | Regex, repeatable |
promtool test rules --diff … | Show expected vs. actual differences in color | Experimental |
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.
rule_files relative paths in the test file.MyappHighErrorRate ’s sum by (namespace) to sum (looks harmless), then re-extract and run:
promtool test rules --run 'HighErrorRate' rules/tests/myapp.test.ymlFailure 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.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 )..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.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).
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'.
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
Official documentation
Video storyboard (about 75 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.
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.
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.
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.
Module 7 · Black-box monitoring: blackbox exporter and synthetic probes
- 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
ProbeCRs (release: kps) to probe the myapp internal address and an external HTTPS site. - Read
probe_success,probe_http_status_code,probe_phase_duration_secondsandprobe_ssl_earliest_cert_expiry, write alerts for probe failure and certificate expiry, then usedebug=trueto troubleshoot.
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.
| Metric | Meaning | Typical alert |
|---|---|---|
probe_success | 1 = probe succeeded (all module conditions met) | probe_success == 0 for 2m |
probe_duration_seconds | Total probe duration | > 2s for 10m |
probe_phase_duration_seconds{phase} | http phases: resolve, connect, tls, processing, transfer | Find whether DNS or TLS is slow |
probe_http_status_code | Status code of the last response | Diagnostic aid |
probe_ssl_earliest_cert_expiry | Earliest expiry time in the certificate chain (Unix seconds) | < 14 days away |
probe_dns_lookup_time_seconds | DNS resolution time | — |
Why: white-box and black-box complement each other
- myapp's
myapp_http_requests_totalonly 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
- The Operator translates the Probe CR into one job (
job_name: probe/<ns>/<name>,joblabels come fromspec.jobName): static targets become__address__, relabeling:__address__ → __param_target,__param_target → instance,__address__ = spec.prober.url,__param_module = spec.module,metrics_path = /probe. - 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. - 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'stimeout). - 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. - 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”.
/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
Deployment topology: where to probe from
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).
Core commands
| Command | Purpose | Notes |
|---|---|---|
helm upgrade --install blackbox prometheus-community/prometheus-blackbox-exporter -n monitoring --version 11.21.3 -f … | Install | Service blackbox-prometheus-blackbox-exporter:9115 |
curl 'localhost:9115/probe?target=…&module=…&debug=true' | Probe manually and print debug logs | First step in troubleshooting |
kubectl get probe -A | List Probe CRs | Also requires release: kps |
curl localhost:9115/config | View the effective module configuration | Confirm 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).
manifests/blackbox/, let Argo CD sync it; in Prometheus → Targets, you should see probe/monitoring/myapp-http/… and probe/monitoring/external-https/…, all UP./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.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
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.< 90, and check whether the external site triggers it (depends on how many days its certificate has left), then change it back.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-labelsdebug 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())"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'
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
Official documentation
- prometheus/blackbox_exporter (CONFIGURATION.md)
- Understanding and using the multi-target exporter pattern
- prometheus-blackbox-exporter chart
- Probe CRD (API reference)
Video storyboard (about 75 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.
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.
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.
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.
Module 8 · First five hours: recap, self-test and cleanup
- 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).
What: knowledge map of the first five hours
| Lesson | Topic | Core output | Its “as code” form in this lesson |
|---|---|---|---|
| Lesson 1 | Prometheus architecture, metric types, PromQL, Grafana basics | myapp /metrics,prometheus.yml, RED dashboards | ServiceMonitor generates scrape_configs; dashboard ConfigMap / Grafonnet |
| Lesson 2 | Alerting rules, Alertmanager, production readiness | rules/*.yml, routing and inhibition | PrometheusRule + promtool unit tests |
| Lesson 3 | Azure Monitor managed Prometheus + Azure Managed Grafana | Managed collection and storage (CRD group azmonitoring.coreos.com) | Terraform grafana provider manages resources in AMG |
| Lesson 4 | AMP + AMG | Managed scraper, remote_write SigV4 | Same as above; rule groups are tested from the same source files |
| Lesson 5 (this lesson) | Operator, GitOps, monitoring as code | monitoring-config repository | — |
| Lesson 6(next lesson) | Architecture in practice: Thanos / Mimir, multi-cluster, SLOs | Extend on this lesson's kind environment | add 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
| Stage | Artifacts | Verification | What you see when it fails |
|---|---|---|---|
| ① Commit | ServiceMonitor, PrometheusRule, Probe, dashboards, values | PR review | — |
| ② CI | build/*.rules.yml, dashboards/build/*.json | promtool check/test, jq, jsonnetfmt, terraform plan, kubeconform (including CRD schema) | PR turns red |
| ③ GitOps | CRs and ConfigMaps in the cluster | ServerSideApply, admission webhook, sync wave | OutOfSync / Degraded, webhook rejection |
| ④ Operator | prometheus.yaml.gz, rulefiles ConfigMap | selector matching, object validity | Operator logs; (silent) missing job |
| ⑤ Prometheus | targets, rule evaluation | config-reloader,prometheus_config_last_reload_successful | PrometheusBadConfig, 0/0 up |
| ⑥ Alerting | Alertmanager notifications | Watchdog (dead man's switch), thresholds tested with promtool | No notifications / alert storms |
| ⑦ Visualization and probing | Grafana dashboards, probe_success | sidecar logs, provisioned marker, black-box alerts | dashboard missing, ProbeFailed |
When: self-assessed maturity
| Level | Characteristics |
|---|---|
| L1 Manual | helm install + build dashboards and alerts in the UI |
| L2 Declarative | ServiceMonitor / PrometheusRule / dashboard ConfigMaps in Git, applied manually |
| L3 GitOps | Argo CD / Flux reconciles; CRDs managed separately; UI read-only |
| L4 Testing | rule unit tests, dashboard build and validation, Terraform plan in PRs |
| L5 Closed loop | black-box + white-box + SLO (Lesson 6); alerts include a runbook and dashboard links; regular drills |
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
Resource list for this lesson (keep / can delete)
| Resource | Location | Needed for Lessons 6–7? |
|---|---|---|
| kind cluster lab | Local Docker | Keep |
| kps (release kps) + CRDs | monitoring | Keep (Lesson 6 modifies the values to add Thanos) |
| myapp + ServiceMonitor + PrometheusRule | myapp | Keep (data source for the SLO and cardinality experiments) |
| blackbox + Probe | monitoring | Keep (availability SLO) |
| Argo CD and the three Applications | argocd | Recommended to keep |
| Grafana resources created by Terraform, service account token | Grafana | Can delete (terraform destroy) |
| alert-sink echo service | monitoring | Can 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.
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.
chmod +x , then run it; for each ✗, use the troubleshooting tree below to locate the cause.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).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'
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 -c2. 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'
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
Official documentation
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration are provided instead.
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.
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.
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.
Command cheat sheet
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
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=50kubectl -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'
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
doneargocd 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
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/reloadjb 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
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
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
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
| Symptom | Most likely cause | First command |
|---|---|---|
| My job is not in /targets at all | ServiceMonitor missing release: kps | kubectl get smon -A -l 'release!=kps' |
| job exists but 0/0 up | Service labels / port name / namespaceSelector mismatch | kubectl -n myapp get svc --show-labels |
| target DOWN 404 | Wrong path or port | curl -si localhost:5000/metrics |
| PrometheusRule apply rejected | PromQL syntax error (webhook) | promtool check rules |
| Rule does not appear on the Rules page | Missing label / reload failed | logs … -c config-reloader |
| Argo CD: annotations Too long | ServerSideApply not enabled | syncOptions: [ServerSideApply=true] |
| After upgrade, the Operator reports CRD-related errors | CRD not upgraded | Compare the CRD annotation version with appVersion |
| All ServiceMonitors lost after renaming | releaseName changed | helm.releaseName: kps |
| Dashboard does not load | label value is not "1" / JSON error | sidecar and grafana container logs |
| panel Datasource ${DS_PROMETHEUS} not found | Exported in the “external sharing” format | change the uid to prometheus |
| terraform plan always shows a diff | JSON contains id/version | Delete these fields |
| probe scrape DOWN (deadline exceeded) | module timeout ≥ scrape timeout | debug=true |
Recommended config snippets
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- 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
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'
release: kps; verify both Pods are up.terraform plan to detect the drift.--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./healthz and two external HTTPS sites; add ProbeFailed, ProbeSlow, TLSCertExpiringSoon and their promtool tests.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.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
| Topic | Verified findings | Source (accessed 2026-11-15) |
|---|---|---|
| kube-prometheus-stack | 93.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 CRDs | chart source (Chart.yaml, values.yaml, _helpers.tpl, README) · UPGRADE.md · Releases |
| prometheus-operator-crds chart | 33.0.2, appVersion v0.95.2 | chart |
| Prometheus Operator | v0.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.static | CHANGELOG · API reference · v0.95.2 source (pkg/prometheus, pkg/operator, example/prometheus-operator-crd) |
| Prometheus / promtool | Prometheus 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_exporter | Alertmanager v0.35.0 (2026-11-09); node_exporter v1.12.1 (2026-07-14) | each project's GitHub Releases |
| Grafana | Grafana 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 provider | v4.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 |
| Grafonnet | no 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 sizes | grafana/grafonnet(README, gen/…/custom/util/grid.libsonnet) |
| blackbox exporter | blackbox_exporter v0.29.1 (2026-10-21); prometheus-blackbox-exporter chart 11.21.3 (appVersion v0.29.1), default module http_2xx | blackbox_exporter · chart · multi-target exporter guide |
| GitOps tools | Argo 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 CreateReplace | Argo CD Sync Options · Flux HelmReleases |
| CI action versions | actions/checkout v7.0.1; actions/upload-artifact v7.0.2 | GitHub Releases (queried via API) |
| Facts carried over from prerequisite courses | kind v0.33.0 / Kubernetes 1.37, Helm 4.3.x, Terraform 1.17.x | See 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.disabledto turn them off); whether an Argo CD webhookcaBundledrift 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'sgrafana/helm-chartslinks 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.