Narration: every write request passes through this pipeline, and extension points plug into a few fixed positions along it.
Kubernetes Hour 8: Extending Kubernetes — CRDs, Operators and Service Mesh
lab built in hour 1, with no cloud costs.- Explain what each Kubernetes API extension method (CRDs, aggregated APIs, admission webhooks / ValidatingAdmissionPolicy, controllers) solves, and choose the right extension point for a given requirement.
- Write production-grade CRDs: structural schemas, defaults and pruning,
x-kubernetes-validations(CEL) and transition rules (oldSelf), status / scale subresources, printer columns, multiple versions and conversion webhooks. - Master the controller pattern: list-watch, informer cache, workqueue, level-triggered reconcile, idempotency, ownerReferences and garbage collection, finalizers and leader election.
- Use kubebuilder v4 to build a ShopApp Operator from scratch that manages the shop application, and run
make manifests / install / run / deployend to end. - Evaluate existing Operators for selection and risk: OperatorHub, OLM (v0 and v1), capability levels, CRD upgrades and overly broad permissions; install CloudNativePG on kind.
- Understand the value and cost of a service mesh: sidecar vs. Istio ambient (ztunnel / waypoint), mTLS and SPIFFE identity, Gateway API for mesh (GAMMA), and when you should not use a mesh.
- Practice Istio ambient on shop: automatic mTLS, PeerAuthentication STRICT, AuthorizationPolicy, HTTPRoute 90/10 canary, Kiali and Prometheus metrics. Finish with a troubleshooting tree for common extension-related faults.
1-hour timetable
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: kind cluster and extension tools | kind cluster lab (v1.37), Go 1.26, kubebuilder 4.16.0, istioctl 1.32.0, shop namespace ready | — | Install the tools and run a self-check |
| 1 | 00–06 | API extension overview | CRDs, aggregated APIs (APIService), admission webhooks and VAP / MAP, controllers; selection decisions | All extension points a request passes through (CRD request vs. aggregated API request) | Survey the extension points in the lab cluster |
| 2 | 06–13 | CRD deep dive | structural schema, pruning, defaults, CEL rules and oldSelf, ratcheting, status / scale subresources, printer columns, multiple versions and conversion | CRD write validation pipeline | Hand-write the ShopApp CRD and trigger each validation rule |
| 3 | 13–21 | Controller pattern | list-watch, informers, workqueue, level-triggered, idempotency, ownerReferences, finalizers, leader election | Reconcile loop (normal / retry on failure / finalizer deletion) | Build a “poor man’s” controller by hand with kubectl + bash |
| 4 | 21–28 | Operator in practice (kubebuilder) | kubebuilder init / create api, markers, Reconcile, CreateOrUpdate, status conditions, RBAC, envtest | marker → controller-gen → manifests → manager | ShopApp Operator: make run and make deploy |
| 5 | 28–35 | Using existing Operators | OperatorHub, capability levels, OLM v0 / v1 (ClusterExtension), Helm installation, CRD upgrades and permission risks, review checklist | Operator selection scorer | Install CloudNativePG and create a 3-instance PostgreSQL |
| 6 | 35–42 | Service mesh basics | Why you need a mesh; sidecar vs. ambient (ztunnel / waypoint / HBONE); mTLS and SPIFFE identity; GAMMA; when not to use a mesh | An mTLS path through ztunnel / waypoint / sidecar | Reading exercise: write a data-plane selection ADR for shop |
| 7 | 42–50 | Istio in practice | ambient installation, namespace enrollment, PeerAuthentication STRICT, AuthorizationPolicy (L4 / L7), waypoint, HTTPRoute weights, Kiali / Prometheus | Canary weights + mTLS simulator | shop api v1/v2 90/10 canary |
| 8 | 50–60 | Extension review, troubleshooting and self-check | Common CRD / Operator / mesh failures, production review checklist, uninstall order | Fault injection simulator + extension troubleshooting decision tree | Fault injection drill |
| — | After class | Cheat sheet · Capstone lab | ShopApp v1alpha1 → CEL → Operator → finalizer → CNPG database → ambient mTLS → canary → cleanup | Final quiz: 12 questions | Acceptance checklist: 12 items |
Knowledge coverage matrix
| Target skill | Module | Key commands / objects | Lab | Production case |
|---|---|---|---|---|
| Choose the right API extension point | M1 | kubectl api-resources, kubectl get apiservices, kubectl get crd, kubectl get validatingadmissionpolicies | ✓ | ✓ |
| Write and evolve CRDs | M2 | openAPIV3Schema, x-kubernetes-validations, subresources, additionalPrinterColumns, kubectl explain | ✓ | ✓ |
| CRD multiple versions and storage version | M2 | spec.conversion, status.storedVersions, StorageVersionMigration | Reading | ✓ |
| Controller mechanics | M3 | kubectl get --watch --output-watch-events, kubectl get lease -n kube-system, ownerReferences, finalizers | ✓ | ✓ |
| Write an Operator with kubebuilder | M4 | kubebuilder init / create api, make manifests install run deploy, kind load docker-image | ✓ | ✓ |
| Select and operate third-party Operators | M5 | kubectl apply --server-side -f cnpg-1.30.2.yaml, ClusterExtension, kubectl auth can-i --as | ✓ | ✓ |
| Understand the mesh data plane | M6 | istio.io/dataplane-mode=ambient, istio-injection=enabled, HBONE 15008 | Reading | ✓ |
| Istio security and traffic | M7 | istioctl install --set profile=ambient, istioctl waypoint apply, PeerAuthentication, AuthorizationPolicy, HTTPRoute | ✓ | ✓ |
| Mesh observability | M7 | istioctl ztunnel-config workloads, istioctl dashboard kiali, istio_requests_total | ✓ | ✓ |
| Extension troubleshooting and review | M8 | kubectl get events, kubectl patch … finalizers, istioctl analyze | ✓ | ✓ |
| End-to-end integration | Capstone lab | All | ✓ | ✓ |
Topics excluded from this hour
| Topic | Reason | Where to learn it |
|---|---|---|
| Full writing of ValidatingAdmissionPolicy / MutatingAdmissionPolicy and admission webhooks | Covered in hour 5; this hour only references it when selecting tools | Hour 5 · Module 6 |
| Gateway API north-south (Gateway + HTTPRoute ingress, TLS termination) | Covered in hour 3; this hour only covers east-west (GAMMA) | Hour 3 · Module 6 |
| Packaging Operators as Helm charts, Argo CD managing CRDs | The delivery toolchain is covered in hour 6 and in the Helm / Argo CD courses | Hour 6 · Module 1, Helm course, Argo CD course |
| Writing an aggregated API server from scratch (apiserver-builder / sample-apiserver) | Rarely needed; cannot be covered in 1 hour | kubernetes/sample-apiserver |
| Istio multicluster, egress gateways, Wasm extensions, hands-on Linkerd / Cilium mesh | Beyond 1 hour | istio.io docs “Multicluster”; official docs of each project |
| Dashboard and alert design for mesh metrics | Belongs in the observability course | Prometheus & Grafana course |
How to use this material
Principles · diagrams · animation · commands · labs · production cases · troubleshooting · quiz · voice · video. Read “principles + diagrams + animation” first to build a mental model, then do the “lab” on the kind cluster
lab.A module counts toward progress when you score ≥ 70% on its quiz or click “Mark this module complete”. Progress is saved in this browser (storage key
k8s60-part8-progress-v1).The object that runs through the whole course is
ShopApp (shop.example.com). M2 writes its CRD by hand, M3 explains who makes it take effect, and M4 uses kubebuilder to write the controller. M5 looks at an Operator someone else wrote, and M6–M7 add a mesh to shop.optionalOldSelf GA in v1.33. Commands that were not actually run in this environment are noted on the “Sources” page.Module 0 · Setup: kind cluster and extension tools (kubebuilder, istioctl)
- Completed hours 1–7; familiar with the shop application (namespace
shop: web =nginx:1.29-alpine, api =ghcr.io/stefanprodan/podinfo:6.17.0on port 9898, db =postgres:17). - Lab machine: the hour 1 Azure VM running Ubuntu 24.04 (
Standard_D4s_v5, 4 vCPU / 16 GiB), or Docker Desktop on your own machine. Docker Engine 29.x, kind v0.33.0, kubectl 1.37 and Helm 4 should already be installed. - The hour 7 EKS cluster should already be deleted. This hour creates no cloud costs (the lab VM itself excepted).
Connection to the previous hour
| What we covered earlier | How it is used in this hour |
|---|---|
Hour 1: control loop, the full journey of kubectl apply | A CRD is just “another API resource” that goes through the same apiserver pipeline. An Operator is a control loop you write yourself (M1, M3). |
| Hour 5: RBAC, ServiceAccount, admission control | Operator permission reviews (M4, M5); choosing between webhooks and VAP (M1); mesh identity is based on ServiceAccount (M6) |
| Hour 3: Service, Gateway API | Mesh east-west routing attaches HTTPRoute to a Service (GAMMA, M6–M7) |
| Hour 6: Helm, GitOps, observability | Delivery order for Operators and CRDs; Prometheus scrapes mesh metrics (M5, M7) |
| Hour 7: EKS | The NodePool / NodeClass objects in EKS Auto Mode are themselves a CRD + controller (the example in M1) |
Step 1: confirm (or rebuild) the kind cluster lab and the shop app
kubectl config use-context kind-lab kubectl get nodes kubectl -n shop get deploy,svc
NAME STATUS ROLES AGE VERSION lab-control-plane Ready control-plane 6d v1.37.0 lab-worker Ready <none> 6d v1.37.0 lab-worker2 Ready <none> 6d v1.37.0 NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/api 2/2 2 2 6d deployment.apps/web 2/2 2 2 6d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/api ClusterIP 10.96.41.12 <none> 9898/TCP 6d service/web ClusterIP 10.96.200.7 <none> 80/TCP 6d
If the cluster has been deleted, rebuild it with ~/k8slab/kind-lab.yaml from hour 1, then restore the minimal shop this hour needs:
kind create cluster --config ~/k8slab/kind-lab.yaml # name lab, node image kindest/node:v1.37.0 kubectl create ns shop kubectl -n shop create deploy api --image=ghcr.io/stefanprodan/podinfo:6.17.0 --port=9898 --replicas=2 kubectl -n shop create deploy web --image=nginx:1.29-alpine --port=80 --replicas=2 kubectl -n shop expose deploy api --port=9898 kubectl -n shop expose deploy web --port=80 kubectl -n shop rollout status deploy/api
kubectl -n shop scale deploy/web --replicas=1 before M7, and delete the CloudNativePG cluster after M5 finishes.Step 2: install Go (required by kubebuilder)
The kubebuilder quickstart requires Go v1.24.6+. However, since v4.15.0 the scaffolding has moved to Go 1.26, and the code generated by v4.16.0 uses the new(expr) syntax that only exists in Go 1.26. This is why you should install Go 1.26.x directly (check go.dev/dl for the latest patch number).
GO_VERSION=1.26.<x> # open https://go.dev/dl/ to see the latest patch number
curl -LO "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf "go${GO_VERSION}.linux-amd64.tar.gz"
echo 'export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin' >> ~/.bashrc && source ~/.bashrc
go version
sudo apt-get install -y make build-essential # Makefile and cgo dependencies
go version go1.26.x linux/amd64
Step 3: install kubebuilder
curl -L -o kubebuilder "https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH)" chmod +x kubebuilder && sudo mv kubebuilder /usr/local/bin/ kubebuilder version
Version: cmd.version{KubeBuilderVersion:"4.16.0", KubernetesVendor:"1.37.0", GitCommit:"…", BuildDate:"…", GoOs:"linux", GoArch:"amd64"}
latest changes as new versions are released. To pin a version, get the GitHub Releases page and download kubebuilder_linux_amd64 (v4.16.0). The code in this hour is written for the v4.16.0 project layout.
Step 4: install istioctl 1.32.0 (used in M7)
cd ~/k8slab curl -L https://istio.io/downloadIstio | ISTIO_VERSION=1.32.0 sh - export PATH="$HOME/k8slab/istio-1.32.0/bin:$PATH" # recommended: add to ~/.bashrc istioctl version --remote=false istioctl x precheck
client version: 1.32.0 ✔ No issues found when checking the cluster. Istio is safe to install or upgrade!
Istio 1.32 supports Kubernetes 1.33–1.37 (istio.io support matrix, 2026-11-18). istioctl x precheck only checks and does not change the cluster.
Step 5: prepare a working directory and an image registry convention
mkdir -p ~/k8slab/ext && cd ~/k8slab/ext # Operator images are not pushed to a remote registry. Instead, load them straight into the nodes with kind load: # make docker-build IMG=shop-operator:dev && kind load docker-image shop-operator:dev --name lab kubectl api-resources | wc -l # note the current number of resource kinds; M1 will count again
Module 1 · API extension overview: CRDs, aggregated APIs and admission
- List the 4 kinds of extension points (CRDs, aggregated APIs (APIService), admission (webhooks / VAP / MAP) and controllers), and state what each one “extends.”
- Draw the stages a write request passes through in the apiserver, and mark where each extension point plugs in.
- Given a requirement (a new object type, read-only data computed on demand, policy enforcement, automatic remediation), choose the most suitable extension method, and explain why “CRD + controller” is the most common combination.
- Inventory the existing CRDs, APIServices and admission configuration in the lab cluster.
What: which extension points Kubernetes has
The core of Kubernetes is “a generic, extensible REST API plus a set of control loops.” The official docs split extensions into client extensions (kubectl plugins), API extensions and infrastructure extensions (CNI, CSI, CRI, device plugins, scheduler plugins). This hour focuses on the API layer, which has four slots:
| Extension point | What it extends | Where data is stored | Who implements the logic | Typical examples |
|---|---|---|---|---|
| CustomResourceDefinition (CRD) | Adds a new resource type (a new REST path) | The apiserver’s own etcd (same as built-in resources) | The apiserver handles CRUD, validation and watch; the business logic is implemented by a controller | cert-manager’s Certificate, Karpenter’s NodePool, Gateway API’s HTTPRoute, CNPG’s Cluster |
| Aggregated API (API Aggregation, APIService) | Proxies a whole API group/version to your own API server | Decided by your service (it can store nothing and compute on demand) | An extension apiserver you write yourself | metrics-server (metrics.k8s.io), custom metrics adapters |
| Admission | Adds no resources; instead, rewrites or rejects requests before they are written | Stores no data | A webhook service, or a ValidatingAdmissionPolicy / MutatingAdmissionPolicy that runs CEL inside the apiserver | Kyverno, Gatekeeper, Istio sidecar injection, a “no latest image tag” policy |
| Controller (Controller / Operator) | Does not change the API, but observes objects and drives the real world to converge on the desired state | Reads and writes objects through the API | A process running inside (or outside) the cluster that list-watches the apiserver | The Deployment controller, Argo CD, Operators |
Operator = “CRD + a custom controller for that CRD + operational knowledge.” CoreOS introduced the term in 2016: the experience of people operating a stateful system (backups, upgrades, failover) is written down as code.
Why: why not just write an ordinary service
- A consistent API experience: CRD objects automatically get kubectl, RBAC, audit logs, watch, server-side apply, label selectors,
kubectl explainand GitOps tool support. You do not need to write your own REST service, authentication or storage. - Declarative and self-healing: users write only the desired state, and the controller keeps comparing and correcting. After a crash, it re-reads state from the API, so it is naturally idempotent.
- Platform-ready: the platform team can wrap “a microservice should have a Deployment, Service, HPA, PDB and NetworkPolicy” into one
ShopAppobject, so application teams write only about 10 lines of YAML.
How: the path of a write request inside the apiserver
- Authentication (certificates / tokens / OIDC) → authorization (RBAC and others). RBAC for CRD resources works exactly like RBAC for built-in resources:
apiGroups: ["shop.example.com"], resources: ["shopapps"]. - kube-aggregator checks the path. If an
APIServicepoints that group/version at an external service, the request is proxied unchanged (the extension apiserver handles the remaining steps). Otherwise it goes to a built-in resource or to the apiextensions-apiserver, which handles all CRDs. - Mutating admission: built-in plugins → MutatingAdmissionPolicy (CEL, GA in v1.36) → MutatingAdmissionWebhook.
- Object schema validation: built-in types are validated by Go code; CRDs are validated by the OpenAPI v3 schema plus
x-kubernetes-validations(CEL). - Validating admission: ValidatingAdmissionPolicy (CEL, GA in v1.30) and ValidatingAdmissionWebhook are called in parallel.
- Persisted to etcd → watch notifies all controllers → controllers reconcile.
When: how to choose
| Need | Preferred | Why not the others |
|---|---|---|
| A new kind of “declarative object” that the system should act on automatically (such as ShopApp, database clusters, certificates) | CRD + controller | An aggregated API has to maintain its own storage, HA and versioning; the cost is an order of magnitude higher |
| Data is computed on demand and should not be written into etcd (metrics, log queries, virtual resources) | Aggregated API | Every CRD write goes into etcd, so high-frequency data would overwhelm etcd |
Needs non-CRUD verbs or special subresources (such as streaming endpoints like /exec), or a custom storage backend | Aggregated API | CRDs only support the standard verbs and the status / scale subresources |
| Enforce policy on any resource (including built-in ones): labels must be present, privileged containers are forbidden | VAP (CEL); add a webhook only for complex logic or external data | A CRD’s CEL rules can only constrain that CRD itself |
| Only constrains relationships between the CRD’s own fields (min ≤ max, fields that cannot change) | x-kubernetes-validations inside the CRD | No extra webhook to deploy, and it cannot block writes when a webhook goes down |
| Watches existing resources and fills in what is missing automatically (for example, creating a default NetworkPolicy in every namespace) | Controller (does not necessarily need a CRD) | Admission only takes effect at the moment of writing; it cannot handle drift afterwards |
kubectl apply succeeds. ② “An Operator is a special Kubernetes object.” No. It is an ordinary process in a Deployment that reads and writes the API through RBAC. ③ “Validation always needs a webhook.” Since v1.29, CEL rules inside a CRD are GA, and VAP also covers cross-resource policy. Webhooks are only needed for external data or complex logic. ④ “Aggregated APIs and CRDs are just two ways of writing the same thing.” An aggregated API means you run an apiserver yourself (certificates, HA, storage, version compatibility), and the operational cost is far higher than for CRDs.apiserver request pipeline and the four extension points
Extension method decision diagram
Step-by-step animation: the extension points a request passes through
Switch between a “CRD write request” and an “aggregated API read request,” and watch the branches inside the apiserver: which component handles it, which API or Review object is called, and what you can see in the logs.
Command table
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl api-resources | List all resource types (built-in, CRD and aggregated) | --api-group=shop.example.com, -o wide (shows verbs) |
kubectl api-versions | List all group/versions | Appears right after the CRD is installed |
kubectl get crd | List CRDs | -o custom-columns to view group, scope and versions |
kubectl get apiservices | List APIServices (including the built-in Local ones and external services behind aggregation) | When AVAILABLE is False, check MESSAGE |
kubectl get validatingadmissionpolicies,validatingadmissionpolicybindings | CEL admission policy | Hour 5 M6 |
kubectl get mutatingwebhookconfigurations,validatingwebhookconfigurations | Admission webhook | Check failurePolicy and namespaceSelector |
kubectl get --raw /apis/<group>/<version> | Read the discovery document directly | Troubleshoot “server doesn’t have a resource type” |
1. Inventory all non-built-in resources in the cluster
kubectl get crd -o custom-columns=NAME:.metadata.name,GROUP:.spec.group,SCOPE:.spec.scope,VERSIONS:.spec.versions[*].name kubectl get apiservices | grep -v Local
NAME GROUP SCOPE VERSIONS gatewayclasses.gateway.networking.k8s.io gateway.networking.k8s.io Cluster v1,v1beta1 gateways.gateway.networking.k8s.io gateway.networking.k8s.io Namespaced v1,v1beta1 httproutes.gateway.networking.k8s.io gateway.networking.k8s.io Namespaced v1,v1beta1 envoyproxies.gateway.envoyproxy.io gateway.envoyproxy.io Namespaced v1alpha1 ... NAME SERVICE AVAILABLE AGE v1beta1.metrics.k8s.io kube-system/metrics-server True 6d
How to verify: entries whose SERVICE column is Local are handled inside the apiserver. This includes the groups of all CRDs, which the CRD controller registers automatically as Local APIServices. Only entries that point to a Service are real aggregated APIs. Common error: when metrics-server is not ready, AVAILABLE=False (MissingEndpoints) appears. Then kubectl top fails, and even kubectl api-resources prints discovery-failure warnings. Production use: before a cluster upgrade, inventory CRDs and APIServices and confirm that each one has an owner and a version plan.
2. Check a CRD’s REST path and verbs
kubectl api-resources --api-group=gateway.networking.k8s.io -o wide kubectl get --raw /apis/gateway.networking.k8s.io/v1 | python3 -m json.tool | head -30
NAME SHORTNAMES APIVERSION NAMESPACED KIND VERBS gatewayclasses gc gateway.networking.k8s.io/v1 false GatewayClass delete,deletecollection,get,list,patch,create,update,watch gateways gtw gateway.networking.k8s.io/v1 true Gateway delete,deletecollection,get,list,patch,create,update,watch httproutes gateway.networking.k8s.io/v1 true HTTPRoute delete,deletecollection,get,list,patch,create,update,watch
A CRD resource always supports these 8 standard verbs (plus the status / scale subresources). Verbs that need connect (such as exec and proxy) are only available through aggregated APIs.
3. Admission configuration overview (review of hour 5 content)
kubectl get validatingadmissionpolicies kubectl get mutatingwebhookconfigurations -o custom-columns=NAME:.metadata.name,FAIL:.webhooks[*].failurePolicy,TIMEOUT:.webhooks[*].timeoutSeconds
Common error: if a webhook has failurePolicy: Fail and its service goes down, every matching write request fails. This is the largest blast radius extensions can cause (M8 troubleshooting).
4. What happens to a CRD with no controller
kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: notes.demo.example.com
spec:
group: demo.example.com
scope: Namespaced
names: { plural: notes, singular: note, kind: Note, shortNames: [nt] }
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
text: { type: string, maxLength: 200 }
EOF
kubectl wait --for=condition=Established crd/notes.demo.example.com
kubectl -n shop apply -f - <<'EOF'
apiVersion: demo.example.com/v1
kind: Note
metadata: { name: hello }
spec: { text: "CRD only stores data and has no behavior" }
EOF
kubectl -n shop get nt
customresourcedefinition.apiextensions.k8s.io/notes.demo.example.com created customresourcedefinition.apiextensions.k8s.io/notes.demo.example.com condition met note.demo.example.com/hello created NAME AGE hello 3s
The object was stored, but nothing exists to “execute” it. This is the controller that M3 and M4 will add.
Lab 1: survey the extension points in the lab cluster (about 8 minutes)
kubectl api-resources --no-headers | wc -l
kubectl api-resources --no-headers | awk '{print $(NF-2)}' | cut -d/ -f1 | sort | uniq -c | sort -rn | head
The third column from the end is APIVERSION. Rows without SHORTNAMES have a different column count, so the count is only a reference. Note the number and compare it with the result from module 0.
kubectl get apiservices -o custom-columns=NAME:.metadata.name,SVC:.spec.service.name,NS:.spec.service.namespace,OK:.status.conditions[0].status | grep -v '<none>' kubectl -n kube-system get deploy metrics-server 2>/dev/null || echo "This cluster has no metrics-server (kind does not install it by default)"
kubectl -n shop patch note hello --type=merge -p "{\"spec\":{\"text\":\"$(printf 'x%.0s' {1..201})\"}}"
The Note "hello" is invalid: spec.text: Too long: may not be more than 200 bytes
kubectl auth can-i list notes.demo.example.com -n shop --as=system:serviceaccount:shop:default
no
kubectl get crd notes.demo.example.com -o jsonpath='{.status.conditions[?(@.type=="Established")].status}' outputs True, and kubectl explain note.spec shows the field descriptions.kubectl delete crd notes.demo.example.com. Note that this also deletes all Note objects. In production, always back up the CRs before deleting a CRD (M8).Case 1: the platform team wraps “standard microservices” in a CRD
Problem: 40 teams each copy the Deployment / Service / HPA / PDB / NetworkPolicy templates. Six months later the configurations are inconsistent, and a common security baseline cannot be enforced. Approach: define a WebService CRD in the style of ShopApp, exposing only 4 fields (image, replica range, port, external domain). The Operator generates all child resources and applies consistent labels. Field constraints are written as CEL rules in the CRD. Cross-team rules (no latest tag, owner label required) use VAP. Limits: once a CRD abstraction is published, it must stay compatible for a long time (M2 multiple versions). Use “escape hatch” fields (such as podTemplatePatch) with care, or the abstraction quickly degrades into “just another Deployment.”
Case 2: exposing real-time cost data with an aggregated API
The FinOps team wants kubectl get costs -n shop to return real-time costs. With a CRD, writing every namespace once a minute would generate heavy etcd writes and watch traffic. Approach: write an extension apiserver that registers APIService v1alpha1.cost.example.com. When a request arrives, it queries the cost database in real time, and nothing is written to etcd. Limits: this service must be highly available. When the APIService is unavailable, kubectl api-resources and tools that depend on full discovery (such as namespace deletion and some GitOps tools) report errors or even hang.
Case 3: migrating Gatekeeper webhook rules to VAP
A policy webhook upgrade on one cluster failed and blocked all Pod creation (failurePolicy: Fail). Approach: rewrite the 15 simple rules (labels, image registry allow list, no hostPath) as ValidatingAdmissionPolicy. CEL runs inside the apiserver process with no network calls. Keep only the 2 rules that need external data on the webhook, and add a namespaceSelector to exclude kube-system. See Hour 5 M6 for details.
Common errors and fixes
error: the server doesn't have a resource type "shopapps"
Cause: the CRD is not installed, the name is misspelled, or the CRD was just created and the discovery cache has not refreshed yet. It is also possible that the CRD’s Established condition is False (for example, because of a names conflict).
kubectl get crd | grep -i shopapp
kubectl get crd shopapps.shop.example.com -o jsonpath='{range .status.conditions[*]}{.type}={.status} {.message}{"\n"}{end}'
rm -rf ~/.kube/cache/discovery # clear the local discovery cache and retry
Fix: install the CRD and run kubectl wait --for=condition=Established. In CI, split “install the CRD first, then the CR” into two steps, or use the crds/ directory in Helm or a sync wave in Argo CD.
couldn't get resource list for metrics.k8s.io/v1beta1: the server is currently unable to handle the request
Cause: the aggregated API’s backend service is unavailable (the Pod is not ready, there is a certificate problem, or a NetworkPolicy blocks apiserver access).
kubectl get apiservice v1beta1.metrics.k8s.io -o jsonpath='{.status.conditions[0].message}{"\n"}'
kubectl -n kube-system get pods -l k8s-app=metrics-server
kubectl -n kube-system logs deploy/metrics-server --tail=20
Fix: repair the backend. On kind, metrics-server often fails because of kubelet self-signed certificates, and it needs --kubelet-insecure-tls (lab environments only). If you no longer need it, run kubectl delete apiservice v1beta1.metrics.k8s.io so it does not slow down discovery.
Internal error occurred: failed calling webhook "…": failed to call webhook: Post "https://….svc:443/…": dial tcp …: connect: connection refused
Cause: the admission webhook backend is unavailable, and failurePolicy: Fail is set.
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
kubectl get validatingwebhookconfiguration <name> -o jsonpath='{.webhooks[*].clientConfig.service}'
Fix: restore the backend. In an emergency you can temporarily change failurePolicy to Ignore or delete the configuration, but record the change. Prevention: run at least 2 webhook replicas with a PDB, use a namespaceSelector to exclude kube-system and the webhook’s own namespace, and use VAP for simple rules.
The CustomResourceDefinition "…" is invalid: metadata.name: Invalid value: "…": must be spec.names.plural+"."+spec.group
Cause: the CRD name must exactly equal <plural>.<group>, for example shopapps.shop.example.com.
Fix: change metadata.name or spec.names.plural so they match. The group must be in DNS subdomain format. Use a domain you own, and avoid protected groups such as *.k8s.io, which require an API approval annotation.
1. Use one command to list all group/versions served by aggregated APIs (not local to the apiserver), and show their availability status.
Reference answer
kubectl get apiservices -o custom-columns=NAME:.metadata.name,SERVICE:.spec.service.namespace/.spec.service.name,AVAILABLE:.status.conditions[0].status | grep -v '<none>'
An APIService with an empty spec.service is Local (this includes CRD groups).
2. Determine whether the current user can create shopapps.shop.example.com in the shop namespace, and list all resources in that group.
Reference answer
kubectl auth can-i create shopapps.shop.example.com -n shop kubectl api-resources --api-group=shop.example.com
Scenario analysis: a team has three requirements. ① Developers use one object to describe a “database instance,” and the platform automatically creates a StatefulSet, a backup CronJob and monitoring. ② No namespace may create a Deployment without an owner label. ③ Query the GPU utilization of a Pod over the last 5 minutes live from kubectl. Which extension method would you choose for each?
Reference answer
① CRD + controller (Operator): a declarative object that needs continuous reconciliation and self-healing. ② ValidatingAdmissionPolicy (CEL checking has(object.metadata.labels.owner)); no service needs to be deployed. Only if you must verify that the owner exists in the CMDB do you need a webhook. ③ Aggregated API (or a custom metrics API adapter): real-time data should not be written to etcd.
Lecture video (title and channel verified via YouTube oEmbed, 2026-11-18)
Official docs
- Extending Kubernetes
- Custom Resources (includes a comparison table of CRDs and aggregated APIs)
- Kubernetes API Aggregation Layer
- Operator pattern
Video storyboard script
This course material cannot generate the video or MP3 directly, so the storyboard and narration script are provided.
Narration: every write request passes through this pipeline, and extension points plug into a few fixed positions along it.
Narration: a CRD teaches the API to store a new kind of object, but it is the controller that makes it take effect.
Narration: an aggregated API hands a whole API group to another server. It suits real-time data, and the data does not go into etcd.
Narration: nine out of ten cases are CRD plus controller. For validation alone, use CEL and do not rush to write a webhook.
Module 2 · CRD deep dive: schema, versions, CEL validation and the status subresource
- Write an
openAPIV3Schemathat meets the structural schema requirements, and understand pruning (dropping unknown fields) anddefault. - Use
x-kubernetes-validations(CEL) to express cross-field constraints and “immutable” transition rules (oldSelf), and understand ratcheting and cost budgets. - Enable the status and scale subresources, and configure printer columns and selectableFields.
- Plan multiple versions: served / storage,
status.storedVersions, the conversion strategy (None / Webhook) and storage version migration.
What: the parts of a CRD
| Field | Meaning | Notes |
|---|---|---|
spec.group / names / scope | API group, plural / singular / Kind / short name, Namespaced or Cluster | metadata.name must be <plural>.<group>. Scope cannot be changed after creation. |
versions[] | One schema per version. served controls whether the version is served, and storage controls whether it is the storage version. | Exactly one version with storage: true |
schema.openAPIV3Schema | OpenAPI v3 subset: type, properties, required, enum, minimum, maxLength, pattern, format, default… | Must be structural (every node has a type, no $ref, and anyOf/oneOf/allOf/not are restricted) |
x-kubernetes-validations | CEL rules: rule, message / messageExpression, reason, fieldPath, optionalOldSelf | GA in v1.29. A rule that references oldSelf is a “transition rule” and only runs on updates. |
subresources.status | Enable /status: updates to the main resource ignore status, and updates to /status ignore changes outside spec | Once enabled, only spec changes increment metadata.generation |
subresources.scale | Enable /scale: specReplicasPath, statusReplicasPath, labelSelectorPath | After that you can run kubectl scale, and HPA can act directly on this CR |
additionalPrinterColumns | Columns for kubectl get: name, type, jsonPath, priority | type can be integer / number / string / boolean / date |
selectableFields | Allows --field-selector on these fields | GA in v1.32; up to 8 per version |
conversion | None (only changes apiVersion) or Webhook (calls your conversion service) | A Webhook is required when the schema structure differs |
Why: put constraints in the CRD, not in the controller
- Fail early: an invalid object is rejected at
kubectl apply, and the user sees the error immediately. If validation only happens in the controller, the object has already entered etcd, and the user can only look at status or events. - No dependencies: schema and CEL run inside the apiserver process, so they do not depend on whether a webhook is online.
- Self-documenting:
descriptionappears inkubectl explainand IDE completion. GitOps tools also use the schema for diffs and validation.
How: a few key mechanisms
Pruning: by default, CRDs under apiextensions.k8s.io/v1 drop fields that the schema does not declare (unless the node is marked x-kubernetes-preserve-unknown-fields: true). Since kubectl 1.27, server-side strict field validation is on by default, so a misspelled field name gives you strict decoding error: unknown field instead of being silently dropped.
Defaulting: default is applied when a request is decoded, and also when an object is read from etcd. This means that when you add a field with a default, existing objects also get the default when they are read.
CEL rules: self refers to the value of the node where the rule is placed. A rule on an object node can compare fields (self.minReplicas <= self.maxReplicas). A rule on a field that references oldSelf is a transition rule (self == oldSelf means immutable). When a CRD is created, the apiserver estimates the worst-case cost of each rule and rejects the CRD if the total exceeds the budget. Adding maxLength / maxItems / maxProperties to strings, arrays and maps significantly lowers the estimated cost.
Ratcheting (GA in v1.33): after you tighten validation, invalid fields on existing objects that this update does not change do not block the update. Only the parts you change must satisfy the new rules. Exceptions: required, allOf/oneOf/anyOf/not, list-type and similar constraints, and transition rules that reference oldSelf do not take part in ratcheting.
Multiple versions: each object in etcd is stored in the storage version that was in effect when it was written. When other versions are read, the apiserver converts them. status.storedVersions records every version that has ever been the storage version. To retire an old version, first rewrite all objects to the new storage version (storage version migration), and then remove the old version from storedVersions.
When: rules of thumb for designing CRDs
- Start from
v1alpha1, and keep fields to a minimum. Adding fields is easy; removing them is hard. - spec holds the user’s intent, and status holds the observed facts. status uses standard
conditions(type / status / reason / message / lastTransitionTime / observedGeneration). - Use CEL for constraints between fields and for immutability. When you need to look up other objects (for example, “the referenced Secret must exist”), CEL cannot do it, so put that check in the controller and write the result to status conditions.
- Keep a single object (including status) below the etcd request limit (about 1.5 MiB by default). Put large data in ConfigMaps or object storage, and keep only references in the CR.
x-kubernetes-preserve-unknown-fields: true at the root is the easiest approach.” This turns off pruning and most validation, so there is no real API contract. ② “CEL rules can access other objects.” No. CEL in a CRD can only see the current object (and oldSelf). ③ “Setting served to false for a version means it is retired.” As long as the version is still in storedVersions, etcd may still hold data in that version’s format. ④ “Printer columns affect storage.” They only affect how kubectl get displays results.Structure of the ShopApp CRD
Multiple versions and storage version migration
Step-by-step animation: the validation pipeline a ShopApp passes through on write
Three scenarios: a valid object, a failed CEL rule (the image uses latest), and an update that changes the immutable field tier. Each step shows the real processing done by apiextensions-apiserver and the format of the returned error.
Command table
| Command | Purpose | Key parameters |
|---|---|---|
kubectl apply --server-side -f crd.yaml | Install or update a CRD (for large CRDs, server-side apply is recommended to avoid an overly long last-applied annotation) | --force-conflicts |
kubectl wait --for=condition=Established crd/<name> | Wait for the CRD to become available | --timeout=60s |
kubectl explain shopapp.spec --recursive | View the schema (from the CRD’s description) | --api-version=shop.example.com/v1 |
kubectl get crd <name> -o jsonpath='{.status.storedVersions}' | View the storage versions that have been used | Must check before retiring a version |
kubectl scale shopapp demo --replicas=3 | Scale through the scale subresource | Requires subresources.scale to be enabled |
kubectl patch shopapp demo --subresource=status --type=merge -p … | Write status directly (for debugging) | Requires shopapps/status permission |
kubectl get shopapps --field-selector spec.tier=backend | Filter by selectableFields | v1.32 GA |
kubectl apply --dry-run=server -f cr.yaml | Server-side validation only (including CEL and admission). Nothing is persisted. | Validate CRs in CI |
1. ShopApp CRD (v1alpha1, hand-written version)
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: shopapps.shop.example.com
spec:
group: shop.example.com
scope: Namespaced
names:
kind: ShopApp
listKind: ShopAppList
plural: shopapps
singular: shopapp
shortNames: [shapp] # Do not use sa: it conflicts with ServiceAccount (see the Troubleshooting tab)
categories: [shop] # kubectl get shop includes this resource
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
scale:
specReplicasPath: .spec.replicas
statusReplicasPath: .status.replicas
labelSelectorPath: .status.selector
additionalPrinterColumns:
- { name: Image, type: string, jsonPath: .spec.image }
- { name: Desired, type: integer, jsonPath: .spec.replicas }
- { name: Ready, type: integer, jsonPath: .status.readyReplicas }
- { name: Tier, type: string, jsonPath: .spec.tier, priority: 1 } # shown only with -o wide
- { name: Age, type: date, jsonPath: .metadata.creationTimestamp }
selectableFields:
- jsonPath: .spec.tier
schema:
openAPIV3Schema:
type: object
description: ShopApp describes a stateless service in the shop. The controller generates a Deployment and a Service for it.
properties:
spec:
type: object
required: [image, tier]
x-kubernetes-validations:
- rule: "self.tier != 'frontend' || self.port in [80, 8080]"
message: "port must be 80 or 8080 for the frontend service"
fieldPath: .port
reason: FieldValueInvalid
properties:
image:
type: string
maxLength: 255
description: Container image. It must include an explicit tag. latest is not allowed.
x-kubernetes-validations:
- rule: "self.contains(':') && !self.endsWith(':latest')"
message: "image must include an explicit tag and cannot be latest"
replicas:
type: integer
format: int32
minimum: 0
maximum: 20
default: 2
port:
type: integer
format: int32
minimum: 1
maximum: 65535
default: 9898
message:
type: string
maxLength: 100
description: Passed to podinfo as --ui-message.
tier:
type: string
enum: [frontend, backend]
x-kubernetes-validations:
- rule: "self == oldSelf"
message: "tier cannot be changed after creation"
status:
type: object
properties:
replicas: { type: integer, format: int32 }
readyReplicas: { type: integer, format: int32 }
selector: { type: string }
url: { type: string }
observedGeneration: { type: integer, format: int64 }
conditions:
type: array
maxItems: 8
x-kubernetes-list-type: map
x-kubernetes-list-map-keys: [type]
items:
type: object
required: [type, status]
properties:
type: { type: string, maxLength: 64 }
status: { type: string, enum: ["True", "False", "Unknown"] }
reason: { type: string, maxLength: 128 }
message: { type: string, maxLength: 1024 }
lastTransitionTime: { type: string, format: date-time }
observedGeneration: { type: integer, format: int64 }
kubectl apply --server-side -f shopapp-crd.yaml kubectl wait --for=condition=Established crd/shopapps.shop.example.com kubectl explain shopapp.spec.image
customresourcedefinition.apiextensions.k8s.io/shopapps.shop.example.com serverside-applied
customresourcedefinition.apiextensions.k8s.io/shopapps.shop.example.com condition met
GROUP: shop.example.com
KIND: ShopApp
VERSION: v1alpha1
FIELD: image <string>
DESCRIPTION:
Container image. It must include an explicit tag. latest is not allowed.
How to verify: kubectl get crd shopapps.shop.example.com -o jsonpath='{.status.acceptedNames.kind}' outputs ShopApp. Common mistake: writing a CEL rule on image that references self.tier. self is the node the rule is attached to, so a rule that spans several fields must be written on the shared parent node (spec). Production use: the CRD file lives in Git, and CI runs a regression check with kubectl apply --dry-run=server against every sample CR.
2. Trigger each validation rule
cat > demo.yaml <<'EOF'
apiVersion: shop.example.com/v1alpha1
kind: ShopApp
metadata: { name: demo, namespace: shop }
spec:
image: ghcr.io/stefanprodan/podinfo:6.17.0
tier: backend
message: "hello from ShopApp"
EOF
kubectl apply -f demo.yaml
kubectl -n shop get shopapp demo -o jsonpath='{.spec.replicas} {.spec.port}{"\n"}' # defaults are filled in
kubectl -n shop get shapp -o wide
shopapp.shop.example.com/demo created 2 9898 NAME IMAGE DESIRED READY TIER AGE demo ghcr.io/stefanprodan/podinfo:6.17.0 2 backend 5s
READY is empty because no controller has written status yet (M3 and M4 fill this in). The short name is shapp, not sa, because kubectl gives priority to built-in resources when a short name conflicts.
kubectl -n shop patch shopapp demo --type=merge -p '{"spec":{"image":"nginx:latest"}}'
kubectl -n shop patch shopapp demo --type=merge -p '{"spec":{"replicas":50}}'
kubectl -n shop patch shopapp demo --type=merge -p '{"spec":{"tier":"frontend"}}'
kubectl apply -f - <<'EOF'
apiVersion: shop.example.com/v1alpha1
kind: ShopApp
metadata: { name: typo, namespace: shop }
spec: { image: "nginx:1.29-alpine", tier: frontend, port: 80, replica: 3 }
EOF
The ShopApp "demo" is invalid: spec.image: Invalid value: "string": image must include an explicit tag and cannot be latest The ShopApp "demo" is invalid: spec.replicas: Invalid value: 50: spec.replicas in body should be less than or equal to 20 The ShopApp "demo" is invalid: spec.tier: Invalid value: "string": tier cannot be changed after creation Error from server (BadRequest): error when creating "STDIN": ShopApp in version "v1alpha1" cannot be handled as a ShopApp: strict decoding error: unknown field "spec.replica"
3. The scale and status subresources
kubectl -n shop scale shopapp demo --replicas=3
kubectl -n shop get shopapp demo -o jsonpath='{.spec.replicas} gen={.metadata.generation}{"\n"}'
kubectl -n shop patch shopapp demo --subresource=status --type=merge \
-p '{"status":{"replicas":3,"readyReplicas":3,"selector":"app.kubernetes.io/instance=demo"}}'
kubectl -n shop get shopapp demo -o jsonpath='gen={.metadata.generation}{"\n"}' # writing status does not increase generation
kubectl get --raw /apis/shop.example.com/v1alpha1/namespaces/shop/shopapps/demo/scale
3 gen=2
gen=2
{"kind":"Scale","apiVersion":"autoscaling/v1","metadata":{"name":"demo","namespace":"shop",…},"spec":{"replicas":3},"status":{"replicas":3,"selector":"app.kubernetes.io/instance=demo"}}
4. Add v1: multiple versions and the storage version
versions:
- name: v1alpha1
served: true
storage: false
deprecated: true
deprecationWarning: "shop.example.com/v1alpha1 ShopApp is deprecated; use shop.example.com/v1 instead"
# …same schema as above…
- name: v1
served: true
storage: true
# …if the schema is the same as v1alpha1, conversion can stay None
conversion:
strategy: None # If the structure differs (for example, message moves to spec.ui.message), change this to Webhook:
# strategy: Webhook
# webhook:
# conversionReviewVersions: ["v1"]
# clientConfig:
# service: { namespace: shop-operator-system, name: shop-operator-webhook-service, path: /convert }
# caBundle: … # usually injected by cert-manager's CA injection
kubectl get crd shopapps.shop.example.com -o jsonpath='{.status.storedVersions}{"\n"}' # ["v1alpha1","v1"]
# Option A: rewrite every object once, as-is (each write is saved using the current storage version, v1)
kubectl get shopapps -A -o json | kubectl replace -f -
# Option B: the storage version migration API, GA in v1.37 (storagemigration.k8s.io/v1, StorageVersionMigration object; check the official docs for the exact fields)
kubectl patch crd shopapps.shop.example.com --subresource=status --type=json \
-p '[{"op":"replace","path":"/status/storedVersions","value":["v1"]}]'
Common mistake: removing an old version from storedVersions before the data is migrated, or deleting it directly from versions. The apiserver refuses to delete a version that is still listed in storedVersions. Even if you bypass that check, old-format data may become unreadable. Production use: write every CRD upgrade as a runbook: add the new version, switch storage, migrate, clean up storedVersions, stop serving the old version after at least one release cycle, and then delete it.
Lab 2: Write a ShopApp CRD by hand and trigger each validation rule (about 10 min)
~/k8slab/ext/shopapp-crd.yaml, then run kubectl apply --server-side -f shopapp-crd.yaml and kubectl wait.kubectl -n shop apply -f - <<'EOF'
apiVersion: shop.example.com/v1alpha1
kind: ShopApp
metadata: { name: storefront }
spec: { image: "nginx:1.29-alpine", tier: frontend, port: 9898 }
EOF
The ShopApp "storefront" is invalid: spec.port: Invalid value: "object": port must be 80 or 8080 for the frontend service
Because fieldPath: .port is set, the error points to spec.port instead of spec. After you change it to port: 80, the apply succeeds.
kubectl -n shop apply --validate=false -f - <<'EOF'
apiVersion: shop.example.com/v1alpha1
kind: ShopApp
metadata: { name: pruned }
spec: { image: "nginx:1.29-alpine", tier: backend, foo: bar }
EOF
kubectl -n shop get shopapp pruned -o jsonpath='{.spec}{"\n"}'
{"image":"nginx:1.29-alpine","port":9898,"replicas":2,"tier":"backend"}
foo is silently pruned. This is why strict validation is on by default.
kubectl -n shop get shopapps --field-selector spec.tier=frontend. It should return only storefront.kubectl -n shop get shopapps -o wide shows the Tier column. kubectl get shop -n shop (categories) lists all ShopApps.kubectl -n shop delete shopapp pruned storefront. Keep the CRD and the demo, because M3 still uses them. When you run make install in M4, the kubebuilder-generated CRD with the same name will replace this hand-written CRD.Case 1: Stricter validation blocks updates to existing objects
Problem: on a v1.28 cluster, maximum: 20 was added to replicas. As a result, three existing objects (replicas=30) could not even have a label changed, and GitOps sync got stuck. Fix: after upgrading to a version where ratcheting is GA (v1.33+), invalid fields that you did not change no longer block updates. The controller also writes a Degraded condition on non-compliant objects to push the owning teams to migrate. Limit: a few validations, such as required, do not take part in ratcheting. When you add a new required field, still pair it with a default.
Case 2: The conversion webhook goes down, and the whole Operator goes blind
An Operator switched the CRD storage version to v2, but its controller still used a v1 client to list and watch. After the conversion webhook certificate expired, every v1 list and watch failed. The controller stopped working, and Argo CD could not read these resources either. Fix: cert-manager rotates the webhook certificate automatically and injects caBundle. The webhook runs at least 2 replicas, with a PDB. The controller switches to the storage version as soon as possible. Limit: as long as any client still uses a non-storage version, the webhook is on the critical path.
Case 3: Replace an entire validating webhook with CEL
An internal platform CRD originally used a webhook for 12 validations. After v1.29, the team rewrote 11 of them (ranges, mutual exclusion, immutability, and formats) as x-kubernetes-validations. The one remaining check, "the referenced Secret must exist," became a hint in the controller's status. The result: the webhook Deployment and its certificate management were removed, and upgrades no longer fail with "CR writes fail because the webhook is not ready."
Common errors and fixes
The CustomResourceDefinition "shopapps.shop.example.com" is invalid: spec.validation.openAPIV3Schema…: Forbidden: … must be structural / type: Required value
Cause: the schema is not structural. A node is missing type, or anyOf / additionalProperties is used in a place where it is not allowed, or it is mixed with properties.
Fix: add type at every level of properties and items. For a subtree that needs arbitrary JSON, set x-kubernetes-preserve-unknown-fields: true explicitly on that subtree, not on the root. For int-or-string fields, use x-kubernetes-int-or-string: true.
… x-kubernetes-validations[0].rule: Forbidden: estimated rule cost exceeds budget by factor of … (try adding maxLength, maxItems, or maxProperties)
Cause: CEL cost estimation assumes the worst case. Running all() or matches() over an unbounded array of unbounded strings is estimated as very expensive.
Fix: add maxItems, maxLength, or maxProperties to the relevant arrays, strings, and maps. Put the rule on a smaller subtree. Avoid nested exists checks on large lists.
kubectl get sa returns ServiceAccount instead of ShopApp
Cause: a short name conflict. Built-in resources take priority.
kubectl api-resources | awk '$2=="sa"' kubectl -n shop get shopapps.shop.example.com
Fix: in the CRD, use a short name that does not conflict (such as shapp). Or, in scripts, always use the full <plural>.<group> name.
The CustomResourceDefinition "…" is invalid: status.storedVersions[0]: Invalid value: "v1alpha1": must appear in spec.versions
Cause: you tried to remove a version from spec.versions while it was still listed in storedVersions.
Fix: first rewrite all objects to the new storage version (kubectl get … -o json | kubectl replace -f - or a StorageVersionMigration). Then patch status.storedVersions. Finally, delete the old version.
1. Write a CEL rule for the ShopApp spec: if message is set, it must not contain the string "password".
Reference answer
x-kubernetes-validations:
- rule: "!has(self.message) || !self.message.contains('password')"
message: "message must not contain password"
fieldPath: .messageCheck whether an optional field exists with has() first. Otherwise, evaluating a missing field produces an error.
2. Check which storage versions the ShopApp CRD has used in the past, and validate a CR file with a server-side dry run.
Reference answer
kubectl get crd shopapps.shop.example.com -o jsonpath='{.status.storedVersions}{"\n"}'
kubectl apply --dry-run=server -f demo.yamlScenario analysis: you need to change spec.message (string) to spec.ui.message plus spec.ui.color. The cluster already has 300 v1alpha1 objects, and the CI pipelines of two teams still write v1alpha1. Describe an upgrade plan.
Reference answer
Add v1 with the new structure, and change the conversion strategy to Webhook for a lossless two-way conversion. When converting v1 to v1alpha1, save color in an annotation, and restore it when converting back. Keep the webhook highly available, with cert-manager managing its certificate. Set v1 as the storage version. Mark v1alpha1 as deprecated and give it a deprecationWarning. Switch the controller to a v1 client. Migrate all objects (with StorageVersionMigration or by rewriting them) and clean up storedVersions. Tell both teams to switch to v1 within one release cycle. After that, set v1alpha1 to served: false, check the audit log for no more access, and then delete it.
Teaching video (title and channel verified via YouTube oEmbed, 2026-11-18)
No verifiable video was found that specifically covers CRD CEL validation and storage version migration. Please use the official docs below and the storyboard instead.
Official docs
- Extend the Kubernetes API with CustomResourceDefinitions
- Versions in CustomResourceDefinitions
- Common Expression Language in Kubernetes
- kubebuilder: CRD Validation markers
Video storyboard
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: a CRD is an API contract. Each field's type, range, and default value are written in the schema.
Narration: an invalid object is rejected before it reaches etcd. The controller never sees it.
Narration: a rule that references oldSelf only runs on updates. It is often used to make a field immutable.
Narration: before you retire an old version, first confirm that it is no longer listed in storedVersions.
Module 3 · Controller Patterns: Informers, Reconcile, and Finalizers
- Explain how list-watch, resourceVersion, the informer (Reflector + DeltaFIFO + Indexer), and the workqueue divide the work.
- Explain the difference between level-triggered and edge-triggered logic. Write an idempotent reconcile, and understand why events can be lost or merged.
- Use ownerReference so the garbage collector cleans up child resources. Use a finalizer to clean up resources outside the cluster.
- Understand leader election (Lease), retry backoff,
RequeueAfter, and generation / observedGeneration.
What: The Five Parts of a Controller
| Component | Responsibility | Key details |
|---|---|---|
| Reflector (list-watch) | First LIST to get the full set and a resourceVersion. Then WATCH from that version for incremental events (ADDED / MODIFIED / DELETED / BOOKMARK). | When the watch disconnects, resume from the last resourceVersion. If that version is too old (410 Gone), LIST again. |
| Informer cache (DeltaFIFO + Indexer) | Apply events to the local in-memory cache, and call the event handler functions. | By default, a controller reads from the cache and does not call the apiserver. Within one process, each type gets only one shared informer. |
| Event handler → workqueue | Put the object's key (namespace/name) on the queue. | Each key appears only once in the queue (duplicates merge automatically). Two workers never process the same key at the same time. |
| Reconcile | Read the latest object from the cache by key, compare desired and actual state, create, update, or delete child resources, and write status. | The queue only gives the controller the key, not which event happened. That is what level-triggered means. |
| Retries and backoff | If reconcile returns an error, the key is requeued with exponential backoff. It can also return RequeueAfter to check again later. | By default, controller-runtime applies per-key exponential backoff (starting at milliseconds, capped at about 1000 seconds) on top of an overall rate limit. |
Why: Why Level-Triggered
Edge-triggered logic ("when event X arrives, do Y") needs events that are never lost, never out of order, and processed exactly once. Distributed systems cannot guarantee that. Watches disconnect, processes restart, and several events can arrive back to back while one is being handled. A level-triggered reconcile asks one question each time: "What should the world look like now, what does it look like, and what is the gap to close?" As a result:
- Losing an event is fine. The next event, or the next periodic resync, causes the object to be reconciled again.
- Merging 10 events into one reconcile is fine. The result is the same.
- A crash partway through a reconcile is fine. The reconcile runs again after the restart, and the steps that already completed do not repeat their side effects, because they are idempotent.
How: Key Mechanisms You Must Know
Owns / Watches: the controller watches not only its own CR, but also the child resources it creates (Deployments and Services). When a child changes, it uses the ownerReference to find the owning CR and queues the CR's key. So if someone deletes a Deployment by hand, the controller recreates it right away.
ownerReference and garbage collection: a child's metadata.ownerReferences points to the CR (including its uid, with controller: true). When the CR is deleted, the garbage collector in kube-controller-manager deletes the child resources in cascade. The default is background. With kubectl delete --cascade=foreground, the children are deleted first. Limit: the owner and the child must be in the same namespace (or the owner must be cluster-scoped). It does not work across namespaces, and it cannot manage resources outside the cluster.
Finalizer: when metadata.finalizers has entries, a delete request only sets deletionTimestamp (the object enters Terminating). It does not delete the object. When the controller sees the deletionTimestamp, it runs cleanup, such as deleting cloud DNS records, object storage buckets, or cross-namespace registration entries. After cleanup succeeds, the controller removes its own finalizer, and only then does the apiserver actually delete the object. If the controller is down, the object stays in Terminating.
generation and observedGeneration: once the status subresource is enabled, only a spec change increments metadata.generation by 1. After processing, the controller sets status.observedGeneration to the current generation. This lets users tell whether the controller has seen their latest change. controller-runtime's GenerationChangedPredicate can filter out events that only change status, which reduces useless reconciles.
Leader election: controllers usually run 2 replicas, but only one can reconcile at any moment. Otherwise they would overwrite each other. The replicas compete for a Lease object in coordination.k8s.io/v1. The holder renews the lease regularly. A replica that fails to renew must stop working. kube-controller-manager and kube-scheduler work the same way.
Write conflicts: an Update request carries a resourceVersion. If someone else has changed the object, the apiserver returns 409 Conflict (optimistic locking). The right response is to return an error so the key is requeued. The next time, the controller reads the new version from the cache and recalculates. Or use server-side apply or patch.
When: Controller Design Checklist
- The reconcile depends only on the current state. It does not depend on the event type or on history kept in memory.
- Make every write idempotent: use CreateOrUpdate or server-side apply, with fixed names. Do not create child resources with random names.
- Use ownerReference for child resources inside the cluster. Use a finalizer for resources outside the cluster or in other namespaces.
- When you need to wait for external state, return
RequeueAfter. Do not block the worker withsleepinside reconcile. - Write conditions and observedGeneration to status. Return errors (which triggers backoff), and also write them to conditions and events so users can see them.
Informer and workqueue structure
Deletion flow: finalizers and garbage collection
Step-by-step animation: the reconcile loop
Three scenarios: normal creation, backoff and retry after a child write fails, and deletion with a finalizer. Note the real API call and the controller-runtime log that correspond to each step.
Command table
| Command | Purpose | Key options |
|---|---|---|
kubectl get shopapps -n shop --watch --output-watch-events | See the event stream from the controller's point of view | EVENT column: ADDED / MODIFIED / DELETED |
kubectl get --raw '/apis/…/shopapps?watch=1&resourceVersion=N' | Raw watch stream (JSON events) | allowWatchBookmarks=true |
kubectl get deploy demo -o jsonpath='{.metadata.ownerReferences}' | Check the owner | controller: true marks the managing owner |
kubectl delete shopapp demo --cascade=foreground | Foreground cascading delete (delete children first) | orphan: keep child resources |
kubectl patch shopapp demo --type=json -p '[{"op":"add","path":"/metadata/finalizers","value":["…"]}]' | Add a finalizer by hand (for the lab) | In production, the controller manages this |
kubectl get lease -n kube-system | Check the leader election lock | holderIdentity, renewTime |
kubectl get events -n shop --field-selector involvedObject.kind=ShopApp | Events written by the controller | --sort-by=.lastTimestamp |
1. Watch events through the controller's eyes
kubectl -n shop get shopapps --watch --output-watch-events
kubectl -n shop label shopapp demo team=payments
kubectl -n shop patch shopapp demo --subresource=status --type=merge -p '{"status":{"readyReplicas":1}}'
kubectl -n shop patch shopapp demo --subresource=status --type=merge -p '{"status":{"readyReplicas":1}}' # second time: no change
EVENT NAME IMAGE DESIRED READY AGE ADDED demo ghcr.io/stefanprodan/podinfo:6.17.0 3 3 12m MODIFIED demo ghcr.io/stefanprodan/podinfo:6.17.0 3 3 12m MODIFIED demo ghcr.io/stefanprodan/podinfo:6.17.0 3 1 12m
How to verify: the first ADDED line comes from the initial list when the watch starts. Changing the label and changing the status each produce one MODIFIED. The second status patch, with the same value, is a no-op write. The apiserver does not write to etcd and produces no event. Production use: this is why a controller that writes status triggers another reconcile of itself. As long as the status stops changing, the loop stops on its own.
2. The Lease for leader election
kubectl -n kube-system get lease
kubectl -n kube-system get lease kube-controller-manager -o jsonpath='{.spec.holderIdentity} {.spec.leaseDurationSeconds}s {.spec.renewTime}{"\n"}'
NAME HOLDER AGE kube-controller-manager lab-control-plane_6f0c5d1e-… 6d kube-scheduler lab-control-plane_0b3a1c9d-… 6d lab-control-plane_6f0c5d1e-… 15s 2026-11-18T09:12:44.120931Z
When a kubebuilder-generated Operator runs with --leader-elect, it also creates a Lease in its own namespace. The LeaderElectionID from the scaffold looks like <hash>.example.com. You can see it in the M4 lab.
3. ownerReference and cascade deletion
kubectl -n shop get deploy demo -o jsonpath='{range .metadata.ownerReferences[*]}{.kind}/{.name} controller={.controller} blockOwnerDeletion={.blockOwnerDeletion}{"\n"}{end}'
kubectl -n shop delete deploy demo # while the controller is running: it is recreated immediately
kubectl -n shop get deploy demo -w
Common mistake: writing an ownerReference by hand with the wrong uid. The GC thinks the owner does not exist, so it deletes the child as an orphan. Always use a library function such as controllerutil.SetControllerReference.
Lab 3: Build a "bare-bones" controller with kubectl and bash (about 12 min)
#!/usr/bin/env bash
# Minimal level-triggered ShopApp controller (for teaching only)
set -u
NS=shop
reconcile() {
local name=$1
# 1. Start from the current state. If the object does not exist, do nothing (child resources are left to GC)
if ! kubectl -n "$NS" get shopapp "$name" >/dev/null 2>&1; then
echo "[$(date +%T)] $name: deleted, skipping"; return
fi
local image replicas port uid msg
image=$(kubectl -n "$NS" get shopapp "$name" -o jsonpath='{.spec.image}')
replicas=$(kubectl -n "$NS" get shopapp "$name" -o jsonpath='{.spec.replicas}')
port=$(kubectl -n "$NS" get shopapp "$name" -o jsonpath='{.spec.port}')
uid=$(kubectl -n "$NS" get shopapp "$name" -o jsonpath='{.metadata.uid}')
msg=$(kubectl -n "$NS" get shopapp "$name" -o jsonpath='{.spec.message}')
# 2. Idempotent write: server-side apply, fixed name, with ownerReference
kubectl -n "$NS" apply --server-side --field-manager=poor-controller -f - >/dev/null <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: $name
labels: { app.kubernetes.io/instance: $name, app.kubernetes.io/managed-by: poor-controller }
ownerReferences:
- { apiVersion: shop.example.com/v1alpha1, kind: ShopApp, name: $name, uid: $uid, controller: true, blockOwnerDeletion: true }
spec:
replicas: $replicas
selector: { matchLabels: { app.kubernetes.io/instance: $name } }
template:
metadata: { labels: { app.kubernetes.io/instance: $name } }
spec:
containers:
- name: app
image: $image
args: ["./podinfo", "--port=$port", "--ui-message=$msg"]
ports: [{ containerPort: $port }]
EOF
# 3. Observe the actual state and write it back to status (writing the same value is a no-op, so it does not loop forever)
local ready
ready=$(kubectl -n "$NS" get deploy "$name" -o jsonpath='{.status.readyReplicas}')
kubectl -n "$NS" patch shopapp "$name" --subresource=status --type=merge \
-p "{\"status\":{\"replicas\":$replicas,\"readyReplicas\":${ready:-0},\"selector\":\"app.kubernetes.io/instance=$name\"}}" >/dev/null
echo "[$(date +%T)] $name: desired=$replicas ready=${ready:-0} image=$image"
}
# LIST: process everything once at startup
for n in $(kubectl -n "$NS" get shopapps -o name | cut -d/ -f2); do reconcile "$n"; done
# WATCH: from now on, only care which key changed, not what happened
{ kubectl -n "$NS" get shopapps --watch-only -o name &
kubectl -n "$NS" get deploy -l app.kubernetes.io/managed-by=poor-controller --watch-only -o name &
wait; } | while read -r obj; do reconcile "${obj#*/}"; done
The script assumes the image is podinfo (./podinfo is its command inside the container). Deployment events map straight back to the ShopApp with the same name. A real controller uses ownerReference to map them.
chmod +x poor-controller.sh && ./poor-controller.sh
[09:20:01] demo: desired=3 ready=0 image=ghcr.io/stefanprodan/podinfo:6.17.0 [09:20:03] demo: desired=3 ready=0 image=ghcr.io/stefanprodan/podinfo:6.17.0 [09:20:09] demo: desired=3 ready=3 image=ghcr.io/stefanprodan/podinfo:6.17.0
kubectl -n shop scale shopapp demo --replicas=1 # change the desired state: the controller scales the Deployment down to 1
kubectl -n shop scale deploy demo --replicas=5 # someone changes the child directly: the controller changes it back to 1
kubectl -n shop delete deploy demo # delete the child: the controller recreates it
kubectl -n shop get deploy demo -o jsonpath='{.spec.replicas}{"\n"}'
1
Stop the script (Ctrl+C), change replicas 3 times in a row, then start the script again. The LIST at startup converges directly to the last value. It does not matter that the events in between were "lost."
kubectl -n shop patch shopapp demo --type=json -p '[{"op":"add","path":"/metadata/finalizers","value":["shop.example.com/cleanup"]}]'
kubectl -n shop delete shopapp demo --wait=false
kubectl -n shop get shopapp demo -o jsonpath='deletionTimestamp={.metadata.deletionTimestamp} finalizers={.metadata.finalizers}{"\n"}'
kubectl -n shop get deploy demo # child still exists: the owner has not actually been deleted yet
# simulate the controller finishing cleanup by removing the finalizer:
kubectl -n shop patch shopapp demo --type=json -p '[{"op":"remove","path":"/metadata/finalizers"}]'
sleep 3; kubectl -n shop get shopapp,deploy
shopapp.shop.example.com/demo patched shopapp.shop.example.com "demo" deleted deletionTimestamp=2026-11-18T09:31:05Z finalizers=["shop.example.com/cleanup"] NAME READY UP-TO-DATE AVAILABLE AGE demo 1/1 1 1 11m shopapp.shop.example.com/demo patched No resources found in shop namespace.
Finally, the Deployment is gone too. After the ShopApp is actually deleted, the garbage collector cascades the deletion based on ownerReference.
kubectl apply -f demo.yaml (M4 uses it).Case 1: An edge-triggered controller loses events, and a certificate is not renewed
Problem: an in-house controller issued a certificate whenever it received an ADDED event. Objects created while the controller was restarting were never processed. Fix: switch to level-triggered logic. Reconcile checks whether the certificate exists and has more than 30 days left. If not, it issues one. It returns RequeueAfter set to 30 days before expiry. Limit: RequeueAfter lives only in memory. After a restart, the startup LIST requeues the objects. That is the value of level-triggered logic.
Case 2: Two replicas reconcile at the same time and cause "flapping"
An Operator was deployed with 3 replicas but leader election was not enabled. The three replicas took turns writing different annotations to the same StatefulSet, so rolling updates kept restarting. Fix: enable --leader-elect, with the Lease in the Operator's namespace. Grant RBAC access to coordination.k8s.io/leases. Limit: leader election only guarantees one active leader at a time. There is a gap of more than ten seconds during a handover, so reconcile must tolerate it.
Case 3: A finalizer kept a namespace stuck in deletion for three days
A team uninstalled an Operator (they deleted its Deployment) and then deleted the application namespace. The namespace stayed in Terminating. The CRs inside carried that Operator's finalizer, and nobody was left to remove it. Fix: always uninstall in this order: delete the CRs first and wait for their finalizers to finish, then delete the Operator, and finally delete the CRD. In an emergency, remove the finalizer only after you have confirmed that the external resources were cleaned up by hand. See the M8 troubleshooting tree.
Common errors and fixes
Operation cannot be fulfilled on shopapps.shop.example.com "demo": the object has been modified; please apply your changes to the latest version and try again
Cause: an optimistic locking conflict (409). The controller ran Update with an old object from the cache. In the meantime, someone else changed the object, or the controller's own previous reconcile changed it.
Fix: this is normal. Return an error so the key backs off and retries. To reduce conflicts, write status with Status().Update or Patch instead of updating the whole object, use server-side apply on the spec side, and do not Update the same object several times in one reconcile.
CR stays in Terminating, and kubectl delete hangs
Cause: the finalizer was never removed. The controller is not running, it lacks permission to update the finalizers subresource, or cleanup of an external resource keeps failing.
kubectl -n shop get shopapp demo -o jsonpath='{.metadata.deletionTimestamp} {.metadata.finalizers}{"\n"}'
kubectl -n shop get events --field-selector involvedObject.name=demo --sort-by=.lastTimestamp | tail
kubectl -n shop-operator-system logs deploy/shop-operator-controller-manager --tail=50
Fix: restore the controller first. Only after you have confirmed that the external resources are cleaned up, and as a last resort, run kubectl patch … --type=merge -p '{"metadata":{"finalizers":null}}' (record it in the change ticket).
Controller logs flooded: the same object reconciles dozens of times per second
Cause: every reconcile writes content that looks changed. Examples: writing the current time into status, generating a random annotation each time, or unstable map ordering that makes the spec differ on each run. Each write triggers a watch event, and that event triggers another reconcile.
Fix: write only when something actually changes. A condition's lastTransitionTime should change only when the status value flips (meta.SetStatusCondition handles this). Use GenerationChangedPredicate on the primary resource. When you compare child resources, compare only the fields you manage.
A child resource is deleted by accident: the Deployment disappears right after it is created
Cause: the uid in the ownerReference does not match the owner's actual uid. For example, the owner was deleted and recreated, but the old uid is still used. Or the owner is in a different namespace. The GC decides the owner does not exist and deletes the "orphan."
kubectl -n shop get events --field-selector reason=OwnerRefInvalidNamespace
kubectl -n shop get shopapp demo -o jsonpath='{.metadata.uid}{"\n"}'
Fix: set the ownerReference with a library function. For cross-namespace relationships, use labels and manage cleanup with a finalizer.
1. Watch the Deployments in the shop namespace as watch events, and show the event type.
Reference answer
kubectl -n shop get deploy --watch --output-watch-events
2. Delete the ShopApp demo, but keep the Deployment it created (so the child becomes an orphan).
Reference answer
kubectl -n shop delete shopapp demo --cascade=orphan
kubectl -n shop get deploy demo -o jsonpath='{.metadata.ownerReferences}{"\n"}' # the GC has already removed the owner referenceScenario analysis: your ShopApp controller must register <name>.shop.example.com in the company DNS system when the object is created, and unregister it when the object is deleted. A colleague suggests "call the DNS API to unregister when a DELETED event is received." What is wrong with this approach? What should you do instead?
Reference answer
DELETED events can be lost (the controller goes down, or the watch disconnects). Also, once the object is deleted, the cache no longer has its spec, so the information needed to unregister is gone, and the DNS record would leak permanently. The right approach: add the finalizer shop.example.com/dns when the object is created. In reconcile, if deletionTimestamp is set, call the DNS API to unregister. The call is idempotent, so a missing record counts as success. After success, remove the finalizer. On failure, return an error to back off and retry, and write a Degraded condition. The registration logic is also idempotent: if the record exists, skip it.
Teaching video (title and channel verified via YouTube oEmbed, 2026-11-18)
Official docs
Video storyboard
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: a controller is like a thermostat. It does not care what happened. It only compares the desired state with the actual state.
Narration: an event only reminds you which object needs a look. The queue merges duplicate reminders automatically.
Narration: when something fails, return an error and let the queue retry with exponential backoff. Every step must be idempotent.
Narration: a finalizer makes deletion a two-phase process. ownerReference makes child resources follow automatically.
Module 4 · Operator in Practice: Write an Operator with kubebuilder
- Use
kubebuilder initandcreate apito generate a project. Explain the role ofapi/,internal/controller/,cmd/main.go, andconfig/. - Use markers to declare validation, defaults, subresources, printer columns, and RBAC. Use
make manifeststo generate the CRD and Role. - Write an idempotent Reconcile using CreateOrUpdate and SetControllerReference, a finalizer, status conditions, and observedGeneration.
- Debug locally with
make run. Deploy to the cluster withmake docker-build,kind load, andmake deploy. Read the logs, the Lease, and RBAC.
What: kubebuilder and controller-runtime
kubebuilder is a scaffolding tool maintained by the Kubernetes SIG API Machinery. It generates a Go project, a Makefile, a Dockerfile, and Kustomize manifests. It also uses controller-gen to turn Go types and markers in comments into CRDs, RBAC, and webhook configurations. The runtime library is controller-runtime. It provides the Manager (shared cache, client, leader election, health checks, and metrics), the Controller (workqueue and backoff), and the Reconciler interface. kubebuilder v4.16.0 (2026-09-10) uses controller-runtime v0.25.0 and k8s.io/* v0.37.0, and supports Kubernetes 1.37.
| Directory / file | Contents | Do you edit it? |
|---|---|---|
api/v1alpha1/shopapp_types.go | Spec / Status Go structs + markers | ✓ Define the API |
api/v1alpha1/zz_generated.deepcopy.go | DeepCopy methods (make generate) | ✗ Auto-generated |
internal/controller/shopapp_controller.go | Reconcile, SetupWithManager, RBAC markers | ✓ Business logic |
internal/controller/*_test.go, suite_test.go | Tests based on envtest (real apiserver and etcd binaries) | ✓ Write tests |
cmd/main.go | Create the Manager, register controllers, --leader-elect, metrics and probes | Few |
config/crd/bases/, config/rbac/role.yaml | Generated by make manifests | ✗ Do not edit by hand |
config/default/, config/manager/, config/samples/ | Kustomize overlays for deployment, and sample CRs | As needed |
Why: Why Not Write It with client-go Yourself
- Informers, shared caches, workqueues, rate limiting, leader election, graceful shutdown, and metrics. controller-runtime implements all of these, and many production Operators have validated them.
- Markers make the Go types the single source of truth, so types, validation, and RBAC do not drift apart.
- envtest lets you run integration tests in CI without a cluster. Real apiserver validation, CEL, and the status subresource all take effect. But there is no kube-controller-manager, so a Deployment does not actually create Pods, and the GC does not run.
Similar tools: Operator SDK (from Red Hat; its Go support is built on kubebuilder, and it also offers Helm and Ansible Operators and OLM integration), Kopf (Python), Java Operator SDK, kube-rs (Rust), and Metacontroller (writes logic through webhooks).
How: The Standard Structure of Reconcile
- Get the primary object (from the cache). If NotFound, return nil (it was deleted, and child resources are left to GC).
- Deletion branch: if
DeletionTimestampis set, clean up external resources, remove the finalizer, and return. - Ensure the finalizer: if it is missing, add it and Update.
- Reconcile child resources:
controllerutil.CreateOrUpdate(it does a Get first, then runs your mutate function, and only calls Create or Update if something differs), plusSetControllerReference. - Reconcile external resources: in this example, a registration ConfigMap is written to the
shop-registrynamespace. It is cross-namespace, so ownerReference cannot be used, and a finalizer is required. - Write status: readyReplicas, selector, URL, conditions, and observedGeneration, using
r.Status().Update. - Return: an error means backoff and retry. If you need a timed check, return
ctrl.Result{RequeueAfter: …}. Otherwise, returnctrl.Result{}.
When: When an Operator is worth writing
- Worth it when there is clear operational knowledge to automate (failover, backups, ordered upgrades, certificate rotation). Also worth it when the platform needs a higher-level abstraction than a Deployment and a team can maintain it long term.
- Not worth it when it is just "some YAML with parameters": use Helm or Kustomize. When it is only "validation at write time," use CRD CEL or VAP. When a mature community Operator already exists (for databases, certificates, or message queues), evaluate the existing one first (M5).
make install deploys the Operator." It only installs the CRD. Deploying the controller is make deploy. ② "make run behaves exactly like running in the cluster." A local run uses the permissions in your kubeconfig (usually cluster-admin). A missing RBAC marker will not show up locally, and you only see "forbidden" after deploying. ③ "After changing types.go, there is no need to regenerate." You must run make manifests generate and then make install again. ④ "In Reconcile, r.Get can read a value you just wrote." It reads from the cache, which may not have received the watch event yet. Do not rely on reading right after writing.From Go types to a running controller
Objects managed by the ShopApp Operator
Step-by-step animation: the kubebuilder workflow
Two paths: a local make run (fast debugging, using your kubeconfig permissions) and an in-cluster make deploy (real RBAC and leader election).
Command table
| Command | Purpose | Notes |
|---|---|---|
kubebuilder init --domain example.com --repo example.com/shop-operator | Initialize the project (go.mod, Makefile, cmd/main.go, config/) | Full group name = <group>.<domain> |
kubebuilder create api --group shop --version v1alpha1 --kind ShopApp | Generate the type and controller | Add --resource --controller to skip the interactive prompts |
kubebuilder create webhook --group shop --version v1alpha1 --kind ShopApp --defaulting --programmatic-validation | Generate an admission webhook (requires cert-manager) | For multiple versions, use --conversion (check the book for the exact options) |
make manifests / make generate | Generate CRD, RBAC / DeepCopy | Must be run after changing types or markers |
make install / make uninstall | Install / delete CRD | uninstall deletes all CRs |
make run | Run the controller locally in the foreground | Uses the current kubeconfig |
make test | envtest tests | The first run downloads the etcd / kube-apiserver test binaries |
make docker-build IMG=… / make deploy IMG=… / make undeploy | Build image / deploy / uninstall | kind: insert kind load docker-image in the middle |
make build-installer IMG=… | Generate a single file dist/install.yaml | Easier to distribute and to use with GitOps |
1. Initialize the project
mkdir -p ~/k8slab/ext/shop-operator && cd ~/k8slab/ext/shop-operator kubebuilder init --domain example.com --repo example.com/shop-operator kubebuilder create api --group shop --version v1alpha1 --kind ShopApp --resource --controller tree -L 2 -d .
INFO Writing kustomize manifests for you to edit... INFO Writing scaffold for you to edit... INFO Update dependencies: $ go mod tidy Next: define a resource with: $ kubebuilder create api ... . ├── api │ └── v1alpha1 ├── bin ├── cmd ├── config │ ├── crd │ ├── default │ ├── manager │ ├── rbac │ └── samples ├── hack ├── internal │ └── controller └── test
2. Define the API: api/v1alpha1/shopapp_types.go (replace the Spec and Status types and the type markers)
// ShopAppSpec is the desired state declared by the user.
// +kubebuilder:validation:XValidation:rule="self.tier != 'frontend' || self.port in [80, 8080]",message="the port of a frontend service must be 80 or 8080",fieldPath=".port"
type ShopAppSpec struct {
// Container image. It must carry an explicit tag, and latest is not allowed.
// +required
// +kubebuilder:validation:MaxLength=255
// +kubebuilder:validation:XValidation:rule="self.contains(':') && !self.endsWith(':latest')",message="image must have an explicit tag and cannot be latest"
Image string `json:"image"`
// +optional
// +kubebuilder:default=2
// +kubebuilder:validation:Minimum=0
// +kubebuilder:validation:Maximum=20
Replicas *int32 `json:"replicas,omitempty"`
// +optional
// +kubebuilder:default=9898
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=65535
Port int32 `json:"port,omitempty"`
// Passed to podinfo as --ui-message.
// +optional
// +kubebuilder:validation:MaxLength=100
Message string `json:"message,omitempty"`
// +required
// +kubebuilder:validation:Enum=frontend;backend
// +kubebuilder:validation:XValidation:rule="self == oldSelf",message="tier cannot be changed after creation"
Tier string `json:"tier"`
}
// ShopAppStatus is written by the controller.
type ShopAppStatus struct {
Replicas int32 `json:"replicas,omitempty"`
ReadyReplicas int32 `json:"readyReplicas,omitempty"`
Selector string `json:"selector,omitempty"`
URL string `json:"url,omitempty"`
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// +listType=map
// +listMapKey=type
// +optional
Conditions []metav1.Condition `json:"conditions,omitempty"`
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.selector
// +kubebuilder:resource:shortName=shapp,categories=shop
// +kubebuilder:printcolumn:name="Image",type=string,JSONPath=`.spec.image`
// +kubebuilder:printcolumn:name="Desired",type=integer,JSONPath=`.spec.replicas`
// +kubebuilder:printcolumn:name="Ready",type=integer,JSONPath=`.status.readyReplicas`
// +kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp`
// ShopApp is the schema of the ShopApp API.
type ShopApp struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ShopAppSpec `json:"spec"`
Status ShopAppStatus `json:"status,omitempty"`
}
In the scaffold, ShopAppList and SchemeBuilder.Register in init() stay unchanged. The scaffold comments differ slightly between kubebuilder 4.x minor versions, so follow the files that are generated.
3. Controller: internal/controller/shopapp_controller.go
package controller
import (
"context"
"fmt"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
logf "sigs.k8s.io/controller-runtime/pkg/log"
shopv1alpha1 "example.com/shop-operator/api/v1alpha1"
)
const (
finalizerName = "shop.example.com/registry"
registryNS = "shop-registry"
)
// ShopAppReconciler reconciles a ShopApp object
type ShopAppReconciler struct {
client.Client
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=shop.example.com,resources=shopapps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=shop.example.com,resources=shopapps/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=shop.example.com,resources=shopapps/finalizers,verbs=update
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="",resources=services;configmaps,verbs=get;list;watch;create;update;patch;delete
func (r *ShopAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logf.FromContext(ctx)
// 1. Read the primary object (from the cache)
app := &shopv1alpha1.ShopApp{}
if err := r.Get(ctx, req.NamespacedName, app); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// 2. Delete branch: clean up cross-namespace registrations, then remove the finalizer
if !app.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(app, finalizerName) {
if err := r.unregister(ctx, app); err != nil {
return ctrl.Result{}, err // Back off and retry; the object stays Terminating
}
controllerutil.RemoveFinalizer(app, finalizerName)
if err := r.Update(ctx, app); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
// 3. Ensure the finalizer
if controllerutil.AddFinalizer(app, finalizerName) {
if err := r.Update(ctx, app); err != nil {
return ctrl.Result{}, err
}
}
desired := int32(1)
if app.Spec.Replicas != nil {
desired = *app.Spec.Replicas
}
labels := map[string]string{
"app.kubernetes.io/instance": app.Name,
"app.kubernetes.io/managed-by": "shop-operator",
}
// 4. Deployment: CreateOrUpdate writes only when there is a difference
dep := &appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Name: app.Name, Namespace: app.Namespace}}
op, err := controllerutil.CreateOrUpdate(ctx, r.Client, dep, func() error {
dep.Labels = labels
dep.Spec.Replicas = &desired
if dep.Spec.Selector == nil { // the selector is immutable after creation
dep.Spec.Selector = &metav1.LabelSelector{MatchLabels: labels}
}
dep.Spec.Template.Labels = labels
dep.Spec.Template.Spec.Containers = []corev1.Container{{
Name: "app",
Image: app.Spec.Image,
Args: []string{"./podinfo", fmt.Sprintf("--port=%d", app.Spec.Port), "--ui-message=" + app.Spec.Message},
Ports: []corev1.ContainerPort{{Name: "http", ContainerPort: app.Spec.Port}},
ReadinessProbe: &corev1.Probe{ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{Path: "/readyz", Port: intstr.FromString("http")},
}},
}}
return controllerutil.SetControllerReference(app, dep, r.Scheme)
})
if err != nil {
return ctrl.Result{}, err
}
log.Info("deployment reconciled", "operation", op)
// 5. Service
svc := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: app.Name, Namespace: app.Namespace}}
if _, err := controllerutil.CreateOrUpdate(ctx, r.Client, svc, func() error {
svc.Labels = labels
svc.Spec.Selector = labels
svc.Spec.Ports = []corev1.ServicePort{{Name: "http", Port: app.Spec.Port, TargetPort: intstr.FromString("http")}}
return controllerutil.SetControllerReference(app, svc, r.Scheme)
}); err != nil {
return ctrl.Result{}, err
}
// 6. External (cross-namespace) registration
url := fmt.Sprintf("http://%s.%s.svc:%d", app.Name, app.Namespace, app.Spec.Port)
if err := r.register(ctx, app, url); err != nil {
return ctrl.Result{}, err
}
// 7. status
app.Status.Replicas = desired
app.Status.ReadyReplicas = dep.Status.ReadyReplicas
app.Status.Selector = metav1.FormatLabelSelector(dep.Spec.Selector)
app.Status.URL = url
app.Status.ObservedGeneration = app.Generation
cond := metav1.Condition{Type: "Available", Status: metav1.ConditionFalse, Reason: "Progressing",
Message: fmt.Sprintf("%d/%d replicas ready", dep.Status.ReadyReplicas, desired), ObservedGeneration: app.Generation}
if dep.Status.ReadyReplicas == desired {
cond.Status, cond.Reason = metav1.ConditionTrue, "AllReplicasReady"
}
meta.SetStatusCondition(&app.Status.Conditions, cond)
if err := r.Status().Update(ctx, app); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
func registryName(app *shopv1alpha1.ShopApp) string { return app.Namespace + "-" + app.Name }
func (r *ShopAppReconciler) register(ctx context.Context, app *shopv1alpha1.ShopApp, url string) error {
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: registryName(app), Namespace: registryNS}}
_, err := controllerutil.CreateOrUpdate(ctx, r.Client, cm, func() error {
cm.Data = map[string]string{"url": url, "tier": app.Spec.Tier}
return nil
})
return err
}
func (r *ShopAppReconciler) unregister(ctx context.Context, app *shopv1alpha1.ShopApp) error {
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: registryName(app), Namespace: registryNS}}
return client.IgnoreNotFound(r.Delete(ctx, cm)) // Idempotent: a missing object also counts as success
}
// SetupWithManager: For the primary resource, Owns the child resources (a child change enqueues its owner)
func (r *ShopAppReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&shopv1alpha1.ShopApp{}).
Owns(&appsv1.Deployment{}).
Owns(&corev1.Service{}).
Named("shopapp").
Complete(r)
}
How to verify: go build ./... passes, and after make manifests, config/rbac/role.yaml contains rules for deployments, services and configmaps. Common error: forgetting the update permission on shopapps/finalizers. In a cluster with OwnerReferencesPermissionEnforcement enabled, setting blockOwnerDeletion is rejected. Production use: you can avoid fighting other controllers over fields (such as an HPA changing replicas) by replacing the whole mutate function with server-side apply (client.Apply plus a field manager). This example uses CreateOrUpdate for readability.
4. Generate, install and run locally
kubectl delete crd shopapps.shop.example.com --ignore-not-found # delete the CRD hand-written in M2 (along with the demo) kubectl create ns shop-registry make manifests generate make install make run
/home/azureuser/k8slab/ext/shop-operator/bin/controller-gen rbac:roleName=manager-role crd webhook paths="./..." output:crd:artifacts:config=config/crd/bases
customresourcedefinition.apiextensions.k8s.io/shopapps.shop.example.com created
go run ./cmd/main.go
2026-11-18T09:45:02Z INFO setup starting manager
2026-11-18T09:45:02Z INFO Starting EventSource {"controller": "shopapp", "controllerGroup": "shop.example.com", "controllerKind": "ShopApp", "source": "kind source: *v1alpha1.ShopApp"}
2026-11-18T09:45:02Z INFO Starting Controller {"controller": "shopapp", "controllerGroup": "shop.example.com", "controllerKind": "ShopApp"}
2026-11-18T09:45:02Z INFO Starting workers {"controller": "shopapp", "controllerGroup": "shop.example.com", "controllerKind": "ShopApp", "worker count": 1}
kubectl apply -f ~/k8slab/ext/demo.yaml
kubectl -n shop get shapp,deploy,svc -l app.kubernetes.io/managed-by=shop-operator
kubectl -n shop get shapp demo -o jsonpath='{.status.conditions[0].type}={.status.conditions[0].status} url={.status.url}{"\n"}'
kubectl -n shop-registry get cm
NAME IMAGE DESIRED READY AGE shopapp.shop.example.com/demo ghcr.io/stefanprodan/podinfo:6.17.0 2 2 20s NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/demo 2/2 2 2 20s NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/demo ClusterIP 10.96.88.140 <none> 9898/TCP 20s Available=True url=http://demo.shop.svc:9898 NAME DATA AGE shop-demo 2 20s
5. Deploy to the cluster (kind)
make docker-build IMG=shop-operator:dev kind load docker-image shop-operator:dev --name lab make deploy IMG=shop-operator:dev kubectl -n shop-operator-system rollout status deploy/shop-operator-controller-manager kubectl -n shop-operator-system logs deploy/shop-operator-controller-manager -c manager --tail=5 kubectl -n shop-operator-system get lease
Common error: stop make run before you deploy. Otherwise two instances reconcile at the same time (make run does not enable leader election by default). Use the image tag dev, not latest. The default imagePullPolicy for latest is Always, so kind nodes try to pull from the remote registry and fail (ErrImagePull).
Lab 4: ShopApp Operator from Zero to Deployment (about 20 minutes, completed after class)
make manifests generate && go build ./.... Review the generated output:
grep -n "x-kubernetes-validations" -A3 config/crd/bases/shop.example.com_shopapps.yaml | head -20 sed -n '/rules:/,$p' config/rbac/role.yaml | head -40
make install and make run. In another terminal, create the demo, and confirm the Deployment, the Service, the registry ConfigMap and the status conditions.kubectl -n shop delete deploy demo; sleep 2; kubectl -n shop get deploy demo kubectl -n shop scale shapp demo --replicas=3 kubectl -n shop get shapp demo -w # READY changes from 2 to 3
make run, then deploy following section 5. Next, check that the RBAC permissions are just enough:
SA=system:serviceaccount:shop-operator-system:shop-operator-controller-manager kubectl auth can-i create deployments -n shop --as=$SA kubectl auth can-i delete secrets -n shop --as=$SA kubectl auth can-i update shopapps.shop.example.com/finalizers -n shop --as=$SA
yes no yes
kubectl -n shop delete shapp demo kubectl -n shop-registry get cm shop-demo # already deleted: NotFound kubectl -n shop get deploy,svc demo # already removed by GC kubectl -n shop-operator-system logs deploy/shop-operator-controller-manager -c manager --tail=10
make manifests and then make deploy again, create the demo, and watch the logs for forbidden and for the ShopApp stuck without a status. Then restore the marker and deploy again.kubectl -n shop get shapp demo -o yaml, status.observedGeneration equals metadata.generation. You can explain how permissions differ between make run and running inside the cluster.kubectl -n shop delete shapp --all → make undeploy → make uninstall → kubectl delete ns shop-registry. The order matters; see M8.Case 1: Releasing and Upgrading a Platform Operator
Problem: the platform team's Operator has 3 CRDs, and upgrades often hit the problem of a new controller reading an old schema. Approach: use make build-installer to produce a single-file manifest. Put the CRDs and the controller in two Argo CD Applications, and sync the CRDs first (sync wave -1). CRDs only receive backward-compatible changes (new optional fields plus defaults). Breaking changes follow the multi-version process from M2. The controller must support CRs from at least the N-1 version. Limitation: Helm's crds/ directory creates CRDs only on the first install and does not update them on upgrade. That is one reason to manage CRDs separately.
Case 2: Controller OOM from Caching Every Secret in the Cluster
An Operator needed to read one Secret that a user referenced. The developer called r.Get on the Secret directly, so controller-runtime created a cluster-wide informer for Secrets. On a cluster with 3000 namespaces, memory grew to 4 GiB. Approach: use the Manager's cache options to limit the Secret cache by label or namespace, or use an uncached APIReader for this kind of object. Narrow the RBAC to specific namespaces as well. Limitation: reads that bypass the cache hit the apiserver every time, so control how often they run.
Case 3: envtest Caught a CEL Rule Regression
A refactor accidentally deleted the immutability rule on tier. The envtest case in CI, "create backend → update to frontend → expect rejection", failed immediately. Lesson: write one positive and one negative envtest case for each CEL rule. envtest runs against a real apiserver, so it covers the schema, CEL and the status subresource. Pure unit tests with a fake client do not run these validations.
Common errors and fixes
configmaps is forbidden: User "system:serviceaccount:shop-operator-system:shop-operator-controller-manager" cannot list resource "configmaps" in API group "" at the cluster scope
Cause: the RBAC marker is missing, or you changed the marker but did not run make manifests and make deploy again. Local make run uses your admin credentials, so it does not expose this problem.
grep -n "kubebuilder:rbac" internal/controller/*.go kubectl get clusterrole shop-operator-manager-role -o yaml | sed -n '/rules:/,$p'
Fix: add the marker → make manifests → make deploy IMG=….
no matches for kind "ShopApp" in version "shop.example.com/v1alpha1" / failed to wait for shopapp caches to sync
Cause: the CRD is not installed (you forgot make install, or you deleted the CRD before make deploy). The Manager's informer cannot start, and the Manager exits after a timeout.
Fix: run make install (or make deploy, which also installs the CRD). Confirm with kubectl get crd shopapps.shop.example.com.
Failed to pull image "shop-operator:dev": … pull access denied / ErrImagePull
Cause: the image exists only in local Docker and was not loaded into the nodes with kind load. Or the tag is latest, which causes an Always pull.
docker exec lab-worker crictl images | grep shop-operator kind load docker-image shop-operator:dev --name lab
Deployment.apps "demo" is invalid: spec.selector: Invalid value: …: field is immutable
Cause: the mutate function changes the selector on every run (for example, it changes the label set), but a Deployment's selector is immutable after creation.
Fix: set the selector only when the object is created (see if dep.Spec.Selector == nil in the example code). When you need to change labels, you can add template labels, but keep the selector the same. If the selector really must change, delete and recreate the Deployment.
1. Write the markers so that the ShopApp port field defaults to 9898, has a range of 1–65535, and shows a Port column in kubectl get.
Reference answer
// On the field: // +kubebuilder:default=9898 // +kubebuilder:validation:Minimum=1 // +kubebuilder:validation:Maximum=65535 Port int32 `json:"port,omitempty"` // On the type: // +kubebuilder:printcolumn:name="Port",type=integer,JSONPath=`.spec.port`
Then run make manifests install.
2. Package the Operator as a single install file, and deploy the image shop-operator:0.2.0 to kind.
Reference answer
make docker-build IMG=shop-operator:0.2.0 kind load docker-image shop-operator:0.2.0 --name lab make build-installer IMG=shop-operator:0.2.0 kubectl apply -f dist/install.yaml
Scenario analysis: after the Operator goes live, an HPA is configured to scale the Deployment that the Operator creates directly. As a result, the replica count keeps jumping between the HPA's value and the replicas in ShopApp. What is the cause? Give two ways to fix it.
Reference answer
Two controllers fight over the same field. The HPA writes spec.replicas, and on every reconcile the Operator writes back the value from ShopApp. Fix 1: point the HPA at ShopApp itself. The CRD already enables the scale subresource, so the HPA's scaleTargetRef can point to ShopApp. The Operator stays the only writer of the Deployment's replica count. Fix 2: add a rule to ShopApp that the Operator does not manage replicas when autoscaling is enabled. The Operator switches to server-side apply and does not declare the replicas field, so the HPA owns that field.
Instructional videos (title and channel verified via YouTube oEmbed on 2026-11-18)
Official documentation
- The Kubebuilder Book · Quick Start
- Markers reference
- envtest
- controller-runtime (pkg.go.dev)
- kubebuilder Releases
Video storyboard script
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: two commands give you a complete project. You only need to change the types and Reconcile.
Narration: markers are the single source of truth. make manifests turns them into the CRD and RBAC.
Narration: each part is idempotent. Run it again, and the result does not change.
Narration: a local run uses your own permissions. Only after deploying to the cluster do you get the real least-privilege setup, so test both.
Module 5 · Using Existing Operators: OLM, Maturity and Selection
- Explain the five Operator Capability Levels, and use them to judge how much operations work an Operator can take off your hands.
- Compare four ways to install and upgrade: Helm, raw manifests, OLM v0 and OLM v1.
- Identify the main risks of an existing Operator: CRD upgrades (cluster-scoped, single version), excessive permissions, webhook blast radius, finalizer problems during uninstall, and project health.
- Install CloudNativePG on kind, create a 3-instance PostgreSQL cluster for shop, and practice a failover.
What: where to find them and how to measure them
OperatorHub.io is a catalog maintained by the Operator Framework community. Each entry lists its capability level, install method and maintainer. Artifact Hub also lists many Operator Helm charts and OLM packages. There are five capability levels. They give a rough scale for how much operations work the Operator automates for you:
| Level | Name | Meaning | Example |
|---|---|---|---|
| 1 | Basic Install | Automated installation and configuration | Creates a StatefulSet and Service from the CR |
| 2 | Seamless Upgrades | Supports patch and minor upgrades of the Operator itself and of the managed application | Change the version number in the CR to roll out an upgrade |
| 3 | Full Lifecycle | Full lifecycle: backup, restore, failover, scaling | Scheduled backups to object storage, PITR |
| 4 | Deep Insights | Metrics, alerts, log handling, workload analysis | Exposes Prometheus metrics and alerting rules |
| 5 | Auto Pilot | Automatic scaling, auto-tuning, anomaly detection and self-healing | Adjusts parameters automatically based on load |
Publishers self-declare capability levels. Treat them as a reference only, and verify them against documentation, tests and community feedback.
Why: why run a selection review
- CRDs are cluster-scoped: a cluster can hold only one definition of a given CRD. Two teams can hardly run different major versions of the same Operator. Upgrading a CRD affects every namespace at once.
- Permissions are usually broad: database, certificate and mesh Operators often need cluster-wide read and write access to Secrets, Pods and Services, and sometimes even webhook configurations. If one is compromised, a large part of the cluster is exposed.
- Webhooks and finalizers widen the blast radius: when the Operator is down, a webhook with
failurePolicy: Failblocks writes. If you uninstall in the wrong order, CRs and namespaces get stuck in Terminating. - Long-term dependency: you must keep up with its release cadence and stay compatible with Kubernetes upgrades (API deprecations, new features).
How: four ways to install and upgrade
| Method | Mechanism | Pros | Cons |
|---|---|---|---|
Raw manifests (kubectl apply --server-side -f operator.yaml) | A single YAML file published by the project (CRD + RBAC + Deployment + webhook) | Transparent, easy to audit, easy to put into GitOps | You handle upgrades and rollbacks yourself, and you judge version compatibility yourself |
| Helm Chart | The Chart from hour 6 | Parameterized, with the widest ecosystem | Helm does not upgrade CRDs in the crds/ directory. Handle them separately, as the project documentation describes. |
| OLM v0 (the default on OpenShift) | CatalogSource → Subscription (channel) → InstallPlan → ClusterServiceVersion. OperatorGroup decides the namespaces the Operator watches. | Automatic upgrades, dependency resolution, channel-based releases | Many concepts and complex to debug. On vanilla Kubernetes, you must install it separately. |
| OLM v1 (operator-controller) | ClusterCatalog provides the catalog. ClusterExtension (olm.operatorframework.io/v1) declares which package to install, along with the version range or channel. | A simpler, declarative API that suits GitOps | Supports only some packaging formats and install modes (such as AllNamespaces), and does not do dependency resolution. Check the official documentation. |
apiVersion: olm.operatorframework.io/v1
kind: ClusterExtension
metadata:
name: cert-manager
spec:
namespace: cert-manager
source:
sourceType: Catalog
catalog:
packageName: cert-manager
channels: [stable]
version: ">=1.18.0 <2.0.0" # Version range: automatically receives patch and minor releases
# Earlier versions require spec.serviceAccount (the installer uses its permissions to create resources). The v1.12 release notes say it is deprecated, so follow the documentation for the version you install.
When: selection review checklist (short version)
- Necessity: can a managed service (Azure Database for PostgreSQL, RDS) meet the need? Managed services are usually less work than running a database Operator yourself.
- Project health: maintainers (CNCF project, vendor or individual), number of releases in the last 6 months, issue response times, the supported Kubernetes version matrix, and the security advisory process.
- Capabilities: are upgrades, backup and restore, and failover documented and covered by e2e tests? Does the capability level match what the Operator actually does?
- Permissions: does the ClusterRole read and write Secrets across the whole cluster? Can it be limited to a set of namespaces (the watch namespace parameter)? What are the webhook's failurePolicy and namespaceSelector?
- Operations: metrics, alerts and logs; CRD upgrade steps; uninstall steps; how it works with GitOps (CRD size, server-side apply).
OLM v0 and OLM v1 object relationships
CloudNativePG topology in shop
Interactive: Operator selection scorer
Check the conditions that the Operator you are evaluating meets (the weights come from this hour's review checklist). The scorer gives a risk level and recommendations. Try it once with CloudNativePG and once with an Operator your team is evaluating.
"Prefill with CloudNativePG" is only an example judgment, based on its official documentation and CNCF project status. Your organization must still review it against its own security requirements.
Command table
| Command | Purpose | Notes |
|---|---|---|
kubectl apply --server-side -f https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/cnpg-1.30.2.yaml | Install CloudNativePG 1.30.2 | The CRDs are large, so you must use server-side apply |
kubectl get crd -l <label> / kubectl get crd | grep cnpg.io | List the CRDs the Operator brings | Assess the number and versions of CRDs |
kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa> | Audit the Operator's effective permissions | Focus on secrets, pods/exec and webhook configuration |
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations | grep cnpg | List the webhooks the Operator registers | failurePolicy, namespaceSelector |
kubectl get clustercatalogs,clusterextensions | OLM v1 objects | Install operator-controller first |
kubectl get subscriptions,csv,installplans -A | OLM v0 objects | Common on OpenShift |
1. Install CloudNativePG and audit it
kubectl apply --server-side -f \ https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/cnpg-1.30.2.yaml kubectl -n cnpg-system rollout status deploy/cnpg-controller-manager kubectl get crd | grep cnpg.io kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations | grep -i cnpg
deployment "cnpg-controller-manager" successfully rolled out backups.postgresql.cnpg.io 2026-11-18T10:02:11Z clusterimagecatalogs.postgresql.cnpg.io 2026-11-18T10:02:11Z clusters.postgresql.cnpg.io 2026-11-18T10:02:11Z databases.postgresql.cnpg.io 2026-11-18T10:02:11Z imagecatalogs.postgresql.cnpg.io 2026-11-18T10:02:11Z poolers.postgresql.cnpg.io 2026-11-18T10:02:11Z publications.postgresql.cnpg.io 2026-11-18T10:02:11Z scheduledbackups.postgresql.cnpg.io 2026-11-18T10:02:11Z subscriptions.postgresql.cnpg.io 2026-11-18T10:02:11Z mutatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-mutating-webhook-configuration 3 20s validatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-validating-webhook-configuration 3 20s
The CRD list changes between versions, so follow the actual output.
SA=$(kubectl -n cnpg-system get deploy cnpg-controller-manager -o jsonpath='{.spec.template.spec.serviceAccountName}')
kubectl auth can-i --list --as=system:serviceaccount:cnpg-system:$SA | grep -E 'secrets|pods|webhook|^\*'
kubectl get mutatingwebhookconfiguration cnpg-mutating-webhook-configuration \
-o jsonpath='{range .webhooks[*]}{.name} failurePolicy={.failurePolicy}{"\n"}{end}'
How to verify: record whether the Operator can read and write Secrets cluster-wide, whether it can use pods/exec, and its webhook failure policy. Common error: without --server-side, a large CRD fails with metadata.annotations: Too long (the last-applied annotation exceeds 256 KiB). Production use: paste these three outputs into the Operator admission review form.
2. Create a 3-instance PostgreSQL for shop
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: shop-db
namespace: shop
spec:
instances: 3
# imageName: ghcr.io/cloudnative-pg/postgresql:17 # Set this explicitly to match postgres:17 from hour 4 (check the official image list for the tag)
storage:
size: 1Gi # kind's default StorageClass is standard (local-path)
bootstrap:
initdb:
database: shop
owner: shop
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { memory: 512Mi }
kubectl apply -f shop-db.yaml kubectl -n shop get cluster shop-db -w # about 1–3 minutes kubectl -n shop get pods -l cnpg.io/cluster=shop-db -L role kubectl -n shop get svc -l cnpg.io/cluster=shop-db
NAME AGE INSTANCES READY STATUS PRIMARY shop-db 95s 3 3 Cluster in healthy state shop-db-1 NAME READY STATUS RESTARTS AGE ROLE shop-db-1 1/1 Running 0 90s primary shop-db-2 1/1 Running 0 60s replica shop-db-3 1/1 Running 0 35s replica NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE shop-db-r ClusterIP 10.96.12.31 <none> 5432/TCP 95s shop-db-ro ClusterIP 10.96.140.2 <none> 5432/TCP 95s shop-db-rw ClusterIP 10.96.77.215 <none> 5432/TCP 95s
The role label name on Pods may be role or cnpg.io/instanceRole, depending on the version. Follow the output of kubectl get pod --show-labels.
3. Failover drill
kubectl -n shop delete pod shop-db-1
kubectl -n shop get cluster shop-db -w
kubectl -n shop get cluster shop-db -o jsonpath='primary={.status.currentPrimary}{"\n"}'
shop-db 6m 3 2 Failing over shop-db-2 shop-db 6m 3 3 Cluster in healthy state shop-db-2 primary=shop-db-2
Common error: writing the application connection string with a specific Pod's address. It stops working after a failover. Applications should always connect to shop-db-rw.
Lab 5: Review and Install CloudNativePG (about 12 minutes)
cnpg-audit.txt.kubectl -n shop get secret shop-db-app -o jsonpath='{.data.uri}' | base64 -d; echo
kubectl -n shop run psql --rm -it --restart=Never --image=postgres:17 --env="PGPASSWORD=$(kubectl -n shop get secret shop-db-app -o jsonpath='{.data.password}' | base64 -d)" \
-- psql -h shop-db-rw -U shop -d shop -c "create table orders(id serial primary key, item text); insert into orders(item) values ('book'); select * from orders;"
postgresql://shop:…@shop-db-rw.shop:5432/shop CREATE TABLE INSERT 0 1 id | item ----+------ 1 | book
kubectl auth can-i get secrets -A --as=system:serviceaccount:cnpg-system:$SA
If the output is yes, the Operator can read Secrets across the whole cluster. Record the reason you accept the risk, or the mitigation, on the review form (for example, install it only in a dedicated database cluster).
kubectl -n shop get cluster shop-db shows healthy, and you can explain the difference between the rw, ro and r Services.kubectl -n shop delete cluster shop-db # 1. Delete the CR first (the Operator cleans up the Pods, PVCs and Services) kubectl -n shop get pods,pvc -l cnpg.io/cluster=shop-db # 2. Confirm cleanup kubectl delete -f https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/cnpg-1.30.2.yaml # 3. Delete the Operator and the CRDs
Case 1: Database Operator or Managed Database?
Problem: the team is evaluating CloudNativePG and Azure Database for PostgreSQL Flexible Server on AKS. Approach: decide based on who takes on-call. Use a managed service for the core transactional databases, where the cloud vendor handles the SLA, automatic patching and cross-region replication. Use CNPG for dozens of low-cost internal databases (backups go to Blob, and the platform team manages quotas). For CNPG, create a separate "database node pool + dedicated namespace". Limitation: the Operator reduces operations work, but it does not hand over DBA responsibilities.
Case 2: A Major CRD Upgrade Breaks GitOps Sync
An Operator 2.0 moved its CRD from v1beta1 to v1 and removed the old version. The repository still had v1beta1 CRs, and Argo CD sync reported no matches for kind … in version …/v1beta1. Approach: before upgrading, export with kubectl get <crd> -A -o yaml and convert the manifests in bulk. Upgrade the CRD first and then the controller, as the project documentation describes. Rehearse the full process on a test cluster. Lesson: check the project's version deprecation policy during the review.
Case 3: An Over-Privileged Operator Becomes a Pivot for Lateral Movement
A security audit found that a monitoring Operator had cluster-wide secrets: * and pods/exec. Approach: switch to its namespace mode, which watches only the specified namespaces and uses a Role instead of a ClusterRole. Enable a NetworkPolicy for its namespace to restrict egress. Use a VAP to stop any principal other than the Operator from creating webhook configurations with the same name. See hour 5 RBAC.
Common errors and fixes
The CustomResourceDefinition "clusters.postgresql.cnpg.io" is invalid: metadata.annotations: Too long: must have at most 262144 bytes
Cause: the client-side kubectl apply writes the whole object into the last-applied-configuration annotation, and a large CRD exceeds the annotation size limit.
Fix: use kubectl apply --server-side (add --force-conflicts if needed). In Argo CD, enable the ServerSideApply sync option for the application.
Internal error occurred: failed calling webhook "mcluster.cnpg.io": … no endpoints available for service "cnpg-webhook-service"
Cause: the Operator is not ready yet (just installed, restarting, or short on node resources), but its webhook is already registered.
kubectl -n cnpg-system get pods,endpointslices kubectl -n cnpg-system describe deploy cnpg-controller-manager | sed -n '/Conditions/,$p'
Fix: wait for rollout status to finish before you create the CR. In CI or GitOps, set the CR's sync order to come after the Operator.
The Cluster stays at "Setting up primary", and the Pod is Pending: 0/3 nodes are available: … pod has unbound immediate PersistentVolumeClaims
Cause: there is no default StorageClass, or the StorageClass name is wrong.
kubectl get storageclass kubectl -n shop get pvc -l cnpg.io/cluster=shop-db
Fix: set spec.storage.storageClass to a StorageClass that exists (the kind one is standard). See hour 4 M2.
Deleting the shop namespace is stuck in Terminating: Some content in the namespace has finalizers remaining
Cause: the CRs in the namespace carry the Operator's finalizer, but the Operator has already been uninstalled.
kubectl get ns shop -o jsonpath='{.status.conditions[*].message}{"\n"}'
kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get -n shop --ignore-not-found --show-kind 2>/dev/null | grep -v '^NAME'
Fix: reinstall the Operator so it can finish the cleanup (preferred). Or, after you confirm external resources are handled, remove the CR's finalizer by hand. Prevention: uninstall strictly in the order CR → Operator → CRD.
1. List the verbs the controller ServiceAccount in cnpg-system can perform on secrets.
Reference answer
SA=$(kubectl -n cnpg-system get deploy cnpg-controller-manager -o jsonpath='{.spec.template.spec.serviceAccountName}')
kubectl auth can-i --list --as=system:serviceaccount:cnpg-system:$SA | grep -w secrets2. Check the current primary instance of shop-db, and connect to the database through the rw Service and run select 1.
Reference answer
kubectl -n shop get cluster shop-db -o jsonpath='{.status.currentPrimary}{"\n"}'
kubectl -n shop run q --rm -it --restart=Never --image=postgres:17 \
--env="PGPASSWORD=$(kubectl -n shop get secret shop-db-app -o jsonpath='{.data.password}' | base64 -d)" \
-- psql -h shop-db-rw -U shop -d shop -c 'select 1'Scenario analysis: two business teams share one cluster. Team A needs the 0.4x version of a Kafka Operator, and Team B wants the latest 0.5x version, which has incompatible CRD changes. How should the platform team handle this?
Reference answer
A CRD is cluster-scoped and has a single definition, so two incompatible versions cannot coexist. Options: (1) the platform team standardizes on one version (usually the newer one), writes a migration plan, and helps Team A upgrade its CRs; (2) if the versions cannot be unified in the short term, move one of the teams to a separate cluster (or a virtual cluster approach, which needs separate evaluation); (3) consider a managed Kafka service. Whichever option you choose, treat the Operator as a platform capability. The platform team owns its versions, upgrades and on-call, instead of each team installing its own.
Instructional videos (title and channel verified via YouTube oEmbed on 2026-11-18)
No verified explainer videos for OLM v1 or CloudNativePG were found. Follow the official documentation and the storyboard instead.
Official documentation
- OperatorHub.io
- Operator Capability Levels
- OLM v1 (operator-controller) documentation
- CloudNativePG documentation
- CloudNativePG Releases
Video storyboard script
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: capability levels describe how much operations work an Operator does for you, but the publisher reports them themselves.
Narration: installing an Operator means granting cluster-level permissions to a long-running program. It must be reviewed.
Narration: CloudNativePG encodes primary switchover in its controller. Applications only ever need to connect to the rw Service.
Narration: the uninstall order matters just as much as the install order.
Module 6 · Service Mesh Fundamentals: Sidecars, Ambient and mTLS
- Explain the problems a service mesh solves (zero-trust mTLS, L7 traffic control, unified telemetry), and what NetworkPolicy and Gateway API north-south traffic cannot solve on their own.
- Compare the data path, resource usage and operational differences between sidecar mode and Istio ambient mode (ztunnel handles L4, and waypoint handles L7).
- Explain mesh identity: ServiceAccount → SPIFFE ID → short-lived certificate issued by istiod → mutual TLS authentication.
- Understand how Gateway API is used for a mesh (GAMMA: an HTTPRoute's parentRef points to a Service), and judge when you should not introduce a mesh.
What: what a mesh is made of
- Data plane: the proxies that intercept traffic between services. In sidecar mode, it is an Envoy in each Pod (the
istio-proxycontainer). In ambient mode, it is one ztunnel per node (written in Rust, handles only L4: mTLS, L4 authorization and TCP telemetry). When you need L7 features, deploy a waypoint (Envoy) per namespace or per service. - Control plane: istiod. It translates Kubernetes Services and Gateway API / Istio configuration into proxy configuration (pushed over xDS), and it acts as the CA that issues certificates to workloads.
- Identity: each workload's identity comes from its ServiceAccount, in the form of a SPIFFE ID
spiffe://cluster.local/ns/shop/sa/api, stored in the SAN of its X.509 certificate. Authorization policies decide based on identity, not IP.
Why: why you need one (and when you don't)
| Requirement | Without a mesh | With a mesh |
|---|---|---|
| Service-to-service encryption and mutual authentication | Each application manages its own certificates (almost nobody gets this right) | Automatic mTLS, with automatic certificate issuance and rotation |
| "Only web can call GET /api/* on api" | NetworkPolicy can match only by IP, label or port | AuthorizationPolicy matches by SPIFFE identity + HTTP method / path |
| 90/10 canary, header-based routing, timeouts, retries, circuit breaking | Written in the app or SDK, and inconsistent across languages | Configured uniformly with HTTPRoute / VirtualService |
| Service topology and golden signals | Each application instruments itself | Proxies produce request count, latency and error rate consistently |
When not to use a mesh: you have few services (under ten), and the team cannot operate an extra control plane. You only need north-south ingress (Gateway API is enough). You only need L3/L4 isolation (NetworkPolicy is enough). You only need encryption (consider a CNI's transparent encryption, such as WireGuard). Latency is extremely sensitive and you cannot accept extra proxy hops. A mesh is a platform capability, so introduce it only with a clear security or traffic management need.
How: sidecar and ambient data paths
| Dimension | Sidecar mode | Ambient mode |
|---|---|---|
| How workloads join the mesh | Namespace label istio-injection=enabled. Restart the Pods to inject istio-proxy. | Namespace label istio.io/dataplane-mode=ambient. No Pod restart needed. |
| Traffic interception | iptables in the Pod's network namespace (istio-init or istio-cni) redirects traffic to Envoy on 15001 / 15006 | The istio-cni node agent configures redirection in the Pod's network namespace, and traffic is handed to the ztunnel on the same node |
| mTLS transport | TLS between Envoy and Envoy | HBONE between ztunnel and ztunnel (an mTLS tunnel based on HTTP/2 CONNECT, on port 15008) |
| L7 capabilities | Every sidecar has them | Only traffic that passes through a waypoint has them (deployed on demand, istio.io/use-waypoint) |
| Resource usage | One Envoy per Pod (CPU and memory grow linearly with the number of Pods) | One ztunnel per node plus a few waypoints, usually much lower |
| Upgrades | Upgrading the data plane = restarting all application Pods | Upgrading ztunnel / waypoints is decoupled from application Pods |
| Other | The most complete features and the most mature ecosystem. Jobs must handle sidecar shutdown. | GA since Istio 1.24 (2024-11). Some advanced features are still evolving, so check the feature status on istio.io. |
Gateway API for mesh (GAMMA)
In hour 3, an HTTPRoute attached to a Gateway handled north-south traffic. In a mesh, an HTTPRoute's parentRefs can point to a Service (group: "", kind: Service). This means that all east-west traffic sent to that Service follows this route. Several meshes, including Istio, Linkerd and Cilium, support this model, so routing configuration is no longer tied to one mesh's private CRDs. Istio's own VirtualService and DestinationRule still work.
Sidecar and ambient architecture comparison
Certificates and identity: from ServiceAccount to mTLS
Step-by-step animation: the mTLS path of one request from web to api
Three data planes: ambient (ztunnel only), ambient + waypoint, and sidecar. Watch where traffic is intercepted, where it is encrypted, and which layer's policy is enforced where.
Command table (this module focuses on concepts; use these commands to see the data plane clearly)
| Command | Purpose | Notes |
|---|---|---|
kubectl label ns shop istio.io/dataplane-mode=ambient | Add a namespace to ambient | No Pod restart needed |
kubectl label ns shop istio-injection=enabled | Enable sidecar injection for a namespace | Requires kubectl rollout restart |
istioctl ztunnel-config workloads | Workloads as seen by ztunnel (protocol HBONE / TCP, waypoint) | Confirm whether the workload has joined the mesh |
istioctl ztunnel-config certificates <ztunnel-pod>.istio-system | Certificates held by ztunnel (leaf / root, validity period) | Troubleshoot certificate problems |
istioctl proxy-config secret deploy/<name> -n shop | Certificates held by the sidecar | Sidecar mode |
kubectl -n istio-system logs -l app=ztunnel | grep -E "inbound|outbound" | Connection logs (source / destination identity, byte count) | Check whether traffic goes through ztunnel |
1. Compare the resource overhead of the two data planes (read-only: run after installing in M7)
kubectl -n istio-system get ds ztunnel -o wide kubectl top pod -n istio-system -l app=ztunnel # requires metrics-server kubectl -n shop get pods -o custom-columns=NAME:.metadata.name,CONTAINERS:.spec.containers[*].name
NAME DESIRED CURRENT READY UP-TO-DATE AVAILABLE NODE SELECTOR AGE ztunnel 3 3 3 3 3 kubernetes.io/os=linux 10m NAME CONTAINERS api-7d9c6b8f5d-2xk9p podinfo web-6c8d9f7b4c-q7w2n nginx
How to verify: under ambient, application Pods have only their own containers. In sidecar mode, an extra istio-proxy appears (with native sidecar implementations, it appears in initContainers with restartPolicy: Always). Production use: estimate the cost of each mode as "number of Pods × memory per sidecar" and as "number of nodes × ztunnel memory + waypoints".
2. Check the workload's mesh identity
istioctl ztunnel-config workloads | grep -E 'NAMESPACE|shop'
ZT=$(kubectl -n istio-system get pod -l app=ztunnel -o jsonpath='{.items[0].metadata.name}')
istioctl ztunnel-config certificates "$ZT".istio-system
NAMESPACE POD NAME IP NODE WAYPOINT PROTOCOL shop api-7d9c6b8f5d-2xk9p 10.244.1.12 lab-worker None HBONE shop web-6c8d9f7b4c-q7w2n 10.244.2.9 lab-worker2 None HBONE CERTIFICATE NAME TYPE STATUS VALID CERT SERIAL NUMBER NOT AFTER NOT BEFORE spiffe://cluster.local/ns/shop/sa/default Leaf Available true 4f1c… 2026-11-19T10:20:31Z 2026-11-18T10:18:31Z spiffe://cluster.local/ns/shop/sa/default Root Available true 7a2b… 2036-11-16T09:58:02Z 2026-11-18T09:58:02Z
Common error: every Pod in shop uses the default ServiceAccount, so web and api have the same identity, and authorization policies cannot tell them apart. The M7 lab first creates a dedicated ServiceAccount for each service.
Lab 6: Read-Only Lab, Choosing a Data Plane for shop (about 8 minutes)
kubectl get pods -A --no-headers | wc -l kubectl -n shop get deploy -o custom-columns=NAME:.metadata.name,SA:.spec.template.spec.serviceAccountName,REPLICAS:.spec.replicas kubectl -n shop get networkpolicy
| Question | Your answer |
|---|---|
| Do you have a compliance requirement for service-to-service mTLS? | Yes / No |
| Do you need authorization by identity + HTTP method / path? | Yes / No |
| Do you need L7 traffic management such as canary releases, retries and timeouts? Which services? | … |
| Can the team operate istiod upgrades and mesh failures? | … |
| Conclusion: do not introduce / ambient (L4 only) / ambient + waypoint / sidecar | … |
Case 1: Saving Resources by Migrating from Sidecar to Ambient
Problem: In a cluster with 2000 Pods, sidecars used about 15% of node memory, and every Istio upgrade required a rolling restart of all workloads. Approach: Migrate one namespace at a time. First, verify in a test namespace how well ambient + waypoint covers your existing VirtualService / AuthorizationPolicy objects. Then remove the istio-injection label, add istio.io/dataplane-mode=ambient, and do one rolling restart to remove the sidecars. Deploy a waypoint only in the 6 namespaces that need L7. Limits: Services that depend on sidecar-only features (some EnvoyFilters) stay in sidecar mode for now. The two modes can coexist in the same mesh.
Case 2: Compliance Only Required Encryption, So the Service Never Joined the Mesh
The audit required “encryption of east-west traffic inside the cluster.” After evaluation, the team chose transparent CNI encryption (WireGuard), plus NetworkPolicy for L3/L4 isolation. This adds no extra control plane and no proxy hops. Limits: This approach does not provide workload-identity-based authorization or L7 policy. If a later requirement for “authorization by API path” appears, introduce the ambient mesh then.
Case 3: A Shared ServiceAccount Makes Authorization Policies Ineffective
One team wrote a policy that “only allows frontend to call payments,” but every Deployment used the default ServiceAccount, so the policy effectively allowed the whole namespace. Approach: Give each service its own ServiceAccount (this also prepares for Workload Identity in hour 5), and use a VAP to block Deployments in production namespaces from using the default SA.
Common Errors and Fixes
The namespace has the ambient label, but the ztunnel logs show no connections at all
Causes: The istio-cni node agent is not ready or could not set up redirection for this Pod; the Pod has the label istio.io/dataplane-mode=none; or the Pod uses hostNetwork.
kubectl -n istio-system get ds istio-cni-node ztunnel istioctl ztunnel-config workloads | grep shop # PROTOCOL should be HBONE kubectl -n istio-system logs -l k8s-app=istio-cni-node --tail=30
Sidecar mode: the Pod has only 1 container, with no istio-proxy
Causes: The label was added to the namespace after the Pods were created, and the Pods were not restarted; or the label was written as istio-injection=true; or the Pod has sidecar.istio.io/inject: "false".
kubectl get ns shop --show-labels kubectl -n shop rollout restart deploy/api istioctl analyze -n shop
After restricting by principals in an AuthorizationPolicy, all requests are denied, or all requests are allowed
Causes: The principals are wrong (missing the cluster.local/ prefix, or the wrong SA name); or the caller and the callee use the same ServiceAccount; or the client is not in the mesh (no identity).
kubectl -n shop get pod -l app=web -o jsonpath='{.items[0].spec.serviceAccountName}{"\n"}'
kubectl -n istio-system logs -l app=ztunnel --tail=50 | grep -E 'src.identity|policy'1. Add the shop namespace to the ambient mesh, and confirm that the protocol for api is HBONE.
Reference answer
kubectl label ns shop istio.io/dataplane-mode=ambient istioctl ztunnel-config workloads | grep -E 'shop .*api'
2. Write the identity string for the shop/web workload in the mesh (in the form used in AuthorizationPolicy principals), assuming it uses ServiceAccount web.
Reference answer
cluster.local/ns/shop/sa/web
Scenario analysis: A company has 40 microservices. The security team requires “mTLS between all services, and payments accepts only POST /charge from checkout.” The operations team has only 3 people and is concerned about sidecar resource overhead and upgrade cost. What is your plan?
Reference answer
Choose Istio ambient. Once every namespace joins, you get automatic mTLS (L4) from ztunnel, with no restarts and no sidecar overhead. Deploy a waypoint only for the namespace that holds payments (or for the payments service). On the waypoint, use an AuthorizationPolicy (targetRefs pointing to the payments Service) to restrict principal = the checkout SA, method POST, and path /charge. Add waypoints to other services only when needed. Combine this with PeerAuthentication STRICT to reject plaintext, use NetworkPolicy as a backstop, and give each service its own ServiceAccount.
Lecture video (title and channel verified via YouTube oEmbed, 2026-11-18)
Official docs
- Istio ambient mode overview
- Troubleshoot connectivity issues with ztunnel
- Gateway API for Service Mesh (GAMMA)
- SPIFFE overview
Video storyboard
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: As the number of services grows, these cross-cutting concerns get harder to implement separately in every application. The mesh moves them into the infrastructure.
Narration: Sidecar mode runs one proxy per Pod. Ambient moves L4 down to the node and adds L7 only when needed.
Narration: The mesh identity comes from the ServiceAccount, and authorization is based on identity, not IP.
Narration: A mesh is a platform capability, not the default choice.
Module 7 · Istio in Practice: Traffic Splitting, mTLS and Observability
- Install the ambient profile with istioctl, and identify the three components: istiod, istio-cni-node, and ztunnel.
- Bring shop into the mesh, configure PeerAuthentication STRICT, and verify that plaintext clients outside the mesh are rejected.
- Use AuthorizationPolicy to implement L4 authorization (ztunnel, selector) and L7 authorization (waypoint, targetRefs). Understand that once a waypoint is added, the L4 policy must allow the waypoint identity.
- Use HTTPRoute (parentRef pointing to a Service) to implement a 90/10 canary between api v1 and v2, and observe the results with Prometheus and Kiali.
What: Istio APIs used in this module
| Object | API | Purpose | Who executes it in ambient |
|---|---|---|---|
| PeerAuthentication | security.istio.io/v1 | Inbound mTLS mode: PERMISSIVE (default, accepts both plaintext and mTLS) / STRICT (accepts only mTLS) | ztunnel |
AuthorizationPolicy (selector) | security.istio.io/v1 | L4 authorization: source identity (principals), source namespace, IP, port | Destination ztunnel |
AuthorizationPolicy (targetRefs) | security.istio.io/v1 | L7 authorization: adds HTTP method, path, and headers | waypoint |
Gateway (gatewayClassName: istio-waypoint) | gateway.networking.k8s.io/v1 | Declares a waypoint proxy (generated by istioctl waypoint apply) | istiod creates a Deployment for it |
HTTPRoute (parentRefs: kind: Service) | gateway.networking.k8s.io/v1 | East-west L7 routing: weights, header matching, timeouts, retries | waypoint |
Why: Roll out in the order “security first, then traffic”
Joining the mesh gives you mTLS on the first day (traffic between ztunnels is encrypted automatically) with no configuration changes. Then use STRICT to close the plaintext back door, tighten the call relationships with authorization policies, and only then add a waypoint for L7 canary releases. Each step can be rolled back on its own (delete the corresponding object or remove the namespace label).
How: Some behaviors you must know
- PERMISSIVE vs. STRICT: The default PERMISSIVE mode makes migration easier: clients inside the mesh use mTLS, while plaintext clients outside the mesh can still connect. After STRICT is enabled, connections from clients outside the mesh are rejected directly by ztunnel (they appear as connection resets).
- Authorization is allow-by-default: If no ALLOW policy matches a workload, all requests are allowed. Once an ALLOW policy exists, requests that do not match it are denied. DENY policies take precedence over ALLOW policies.
- A waypoint changes “who is connecting”: After traffic passes through a waypoint, the destination ztunnel sees the source identity as the waypoint's ServiceAccount (default name
waypoint). So an L4 policy that originally allowed only web must add the waypoint identity, and the real “only web is allowed” rule is enforced by the L7 policy on the waypoint. - What an L7 denial looks like: When the waypoint denies a request, it returns HTTP 403
RBAC: access denied. When ztunnel (L4) denies a request, there is no HTTP response; the connection is simply reset. - HTTPRoute weights: Applied per request (not per connection), and they require a waypoint. Without one, ztunnel only performs L4 load balancing.
When: The order for rolling out in production
- Install and run this module on a test cluster, and settle on an Istio version (support matrix: 1.32 supports Kubernetes 1.33–1.37).
- Join namespaces one at a time (PERMISSIVE), and watch the ztunnel logs and Kiali for 1–2 weeks to find callers outside the mesh.
- Configure a dedicated ServiceAccount for each service, then write authorization policies (AUDIT / observe first, then ALLOW).
- Switch to STRICT, and deploy waypoints only for services that need L7.
- Set up an upgrade process: canary upgrades of istiod by revision, rolling upgrades of ztunnel, and follow the Istio support cycle (roughly one minor version every 6–7 months).
Topology of shop after this module
Steps for a canary rollout
Interactive simulator: canary weights and mTLS / authorization
On the left, adjust the v2 weight and send 100 requests. On the right, choose a client and a policy, then watch the ztunnel / waypoint decisions and logs. The rules match the behavior described in the istio.io docs; the numbers are random simulations.
api-v2 weight: 10%
Clients: Method:
Command table
| Command | Purpose | Notes |
|---|---|---|
istioctl install --set profile=ambient --skip-confirmation | Install ambient (istiod + istio-cni + ztunnel) | For sidecar, use profile=default |
istioctl waypoint apply -n shop --enroll-namespace --wait | Deploy a waypoint and label the namespace with istio.io/use-waypoint | istioctl waypoint list -n shop |
istioctl analyze -n shop | Statically check for configuration problems | Also works in CI |
istioctl ztunnel-config workloads | View mesh enrollment status and waypoint bindings | WAYPOINT column |
istioctl dashboard kiali / prometheus | Open the dashboard with port forwarding | For a remote VM, add --address 0.0.0.0 or use an SSH tunnel |
istioctl uninstall --purge -y | Uninstall Istio | Delete the waypoint and the namespace labels first |
1. Install Istio ambient
kubectl get crd gateways.gateway.networking.k8s.io &> /dev/null || \ kubectl apply --server-side -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/experimental-install.yaml istioctl install --set profile=ambient --skip-confirmation kubectl -n istio-system get pods -o wide
|\
| \
| \
...
✔ Istio core installed ⛵️
✔ istiod installed 🧠
✔ CNI installed 🪢
✔ Ztunnel installed 🔒
✔ Installation complete
NAME READY STATUS RESTARTS AGE NODE
istio-cni-node-4hx2m 1/1 Running 0 60s lab-worker
istio-cni-node-9kq7d 1/1 Running 0 60s lab-worker2
istio-cni-node-tz8wv 1/1 Running 0 60s lab-control-plane
istiod-6b7c9d8f5-xp2lk 1/1 Running 0 75s lab-worker
ztunnel-5vn8c 1/1 Running 0 55s lab-worker
ztunnel-gq2xr 1/1 Running 0 55s lab-worker2
ztunnel-r8m4t 1/1 Running 0 55s lab-control-plane
The first line follows the ambient getting-started docs from Istio: skip it if the cluster already has the Gateway API CRDs (the v1.6.3 standard channel installed in hour 3); otherwise, install the v1.6.1 experimental channel (as written in the docs).
2. Prepare shop: a dedicated ServiceAccount and api v2
kubectl -n shop create sa web; kubectl -n shop create sa api kubectl -n shop set serviceaccount deploy/web web kubectl -n shop set serviceaccount deploy/api api kubectl -n shop create deploy api-v2 --image=ghcr.io/stefanprodan/podinfo:6.17.0 --port=9898 -- ./podinfo --port=9898 --ui-message="api v2" kubectl -n shop set serviceaccount deploy/api-v2 api kubectl -n shop expose deploy api --name=api-v1 --port=9898 kubectl -n shop expose deploy api-v2 --port=9898 kubectl -n shop get svc api api-v1 api-v2
3. Enroll, STRICT, and L4 authorization
kubectl label ns shop istio.io/dataplane-mode=ambient
istioctl ztunnel-config workloads | grep shop
kubectl apply -f - <<'EOF'
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata: { name: default, namespace: shop }
spec:
mtls: { mode: STRICT }
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata: { name: api-l4, namespace: shop }
spec:
selector:
matchLabels: { app: api }
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/shop/sa/web"]
EOF
4. Waypoint + L7 authorization + 90/10 canary
istioctl waypoint apply -n shop --enroll-namespace --wait
kubectl apply -f - <<'EOF'
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata: { name: api-l4, namespace: shop } # Update: L4 allows only the waypoint identity
spec:
selector:
matchExpressions: [{ key: app, operator: In, values: [api, api-v2] }]
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/shop/sa/waypoint"]
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata: { name: api-l7, namespace: shop }
spec:
targetRefs:
- { kind: Service, group: "", name: api }
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/shop/sa/web"]
to:
- operation:
methods: ["GET"]
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: { name: api, namespace: shop }
spec:
parentRefs:
- { group: "", kind: Service, name: api, port: 9898 }
rules:
- backendRefs:
- { name: api-v1, port: 9898, weight: 90 }
- { name: api-v2, port: 9898, weight: 10 }
EOF
kubectl -n shop exec deploy/web -- sh -c 'for i in $(seq 1 100); do wget -qO- http://api:9898/; echo; done' \
| grep -o '"message": "[^"]*"' | sort | uniq -c
11 "message": "api v2"
89 "message": "greetings from podinfo v6.17.0"
How to verify: In the output of istioctl ztunnel-config workloads | grep shop, the WAYPOINT column shows waypoint; in kubectl -n shop get httproute api -o yaml, Accepted=True appears under status.parents[].conditions. Common error: An L4 policy is written only for app: api, so the api-v2 Pods have no policy and traffic to them is still allowed. That is why the example uses matchExpressions to cover both versions. Production use: Hand weight changes to tools such as Argo Rollouts / Flagger, which advance them automatically based on metrics.
5. Observability: Prometheus and Kiali
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.32/samples/addons/prometheus.yaml
kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.32/samples/addons/kiali.yaml
kubectl -n istio-system rollout status deploy/kiali
istioctl dashboard kiali --address 0.0.0.0 & # Open http://<VM-IP>:20001 in a browser (or use an SSH tunnel)
istioctl dashboard prometheus &
# Prometheus query: requests per second by destination workload (L7 metrics produced by the waypoint)
# sum by (destination_workload, response_code) (rate(istio_requests_total{destination_service_namespace="shop"}[1m]))
# L4 metrics produced by ztunnel: istio_tcp_connections_opened_total, istio_tcp_sent_bytes_total
Lab 7: shop Enrollment and 90/10 Canary (about 20 minutes)
kubectl -n shop get pods -o custom-columns=N:.metadata.name,SA:.spec.serviceAccountName shows the dedicated SAs for web / api.kubectl create ns legacy kubectl -n legacy run curl --image=curlimages/curl:8.17.0 --command -- sleep 1d kubectl -n shop run curl --image=curlimages/curl:8.17.0 --command -- sleep 1d kubectl -n shop exec deploy/web -- wget -qO- -T 3 http://api:9898/version # allowed kubectl -n shop exec curl -- curl -sS -m 3 http://api:9898/version # SA default: denied by L4 kubectl -n legacy exec curl -- curl -sS -m 3 http://api.shop:9898/version # plaintext: denied by STRICT
{"commit":"…","version":"6.17.0"}
curl: (56) Recv failure: Connection reset by peer
curl: (56) Recv failure: Connection reset by peer
The curl image tag is an example; you can replace it with any image that includes curl. Both kinds of denial happen at L4 and produce no HTTP status code. Use the ztunnel logs to tell the causes apart:
kubectl -n istio-system logs -l app=ztunnel --tail=200 | grep -E 'shop/api|denied|policy' | tail -5
kubectl -n shop exec deploy/web -- wget -qO- -T 3 --post-data='x=1' http://api:9898/api/echo # POST: denied by L7
wget: server returned error: HTTP/1.1 403 Forbidden
The waypoint returns 403, with the response body RBAC: access denied.
kubectl -n shop patch httproute api --type=json -p '[{"op":"replace","path":"/spec/rules/0/backendRefs/0/weight","value":50},{"op":"replace","path":"/spec/rules/0/backendRefs/1/weight","value":50}]'kubectl -n shop delete httproute api; kubectl -n shop delete authorizationpolicy --all; kubectl -n shop delete peerauthentication --all istioctl waypoint delete --all -n shop kubectl label ns shop istio.io/dataplane-mode- istio.io/use-waypoint- kubectl delete -f https://raw.githubusercontent.com/istio/istio/release-1.32/samples/addons/kiali.yaml -f https://raw.githubusercontent.com/istio/istio/release-1.32/samples/addons/prometheus.yaml istioctl uninstall --purge -y && kubectl delete ns istio-system legacy kubectl -n shop delete pod curl; kubectl -n shop delete deploy api-v2; kubectl -n shop delete svc api-v1 api-v2
Case 1: The day STRICT was enabled, Prometheus could no longer scrape metrics
Problem: The monitoring system is outside the mesh and scrapes each service's /metrics over plaintext. After STRICT was enabled, every scrape failed. Approach: During the PERMISSIVE period, first use the ztunnel logs to tally all inbound plaintext sources. Then add an exception for the monitoring scrape port (in sidecar mode you can use portLevelMtls; for port-level settings in ambient, follow the official docs on current support), or bring Prometheus into the mesh too. Lesson learned: Before switching to STRICT, inventory every “caller outside the mesh”: monitoring, health checks, external load balancers, and batch jobs.
Case 2: A 10% canary, but v2 receives 50% of the traffic
In the sidecar era, VirtualService was used for weights. After moving to ambient, developers created only an HTTPRoute and forgot to deploy a waypoint. ztunnel does not understand L7 rules, so it load-balanced at L4 across the endpoints of api-v1 and api-v2 (because the api Service's selector happened to match both versions). Approach: Deploy a waypoint and check the HTTPRoute status. Make the Service's selector match only the stable version, and add the new version to routing through a separate Service.
Case 3: An AuthorizationPolicy caused health checks to fail
After an ALLOW policy was added for payments, its Pods stayed NotReady. Cause: this is sidecar mode. The kubelet's HTTP probes should normally be forwarded by istio-proxy through Istio's probe rewriting mechanism, but the team had disabled rewriting (sidecar.istio.io/rewriteAppHTTPProbers: "false"), so the probe requests were treated as external traffic with no identity and were denied. Approach: Restore probe rewriting, or use a separate health-check port and allow it in the policy. In ambient mode, istio-cni configures kubelet probes to bypass redirection, so this issue does not affect them (follow the official docs).
Common Errors and Fixes
curl: (56) Recv failure: Connection reset by peer (some clients suddenly cannot reach the service after joining the mesh)
Causes: STRICT rejected a plaintext client outside the mesh, or the L4 AuthorizationPolicy rejected that identity.
kubectl get peerauthentication -A kubectl -n shop get authorizationpolicy -o wide kubectl -n istio-system logs -l app=ztunnel --tail=300 | grep -iE 'deny|denied|policy|rbac' | tail
Fix: Bring the client into the mesh, or temporarily switch back to PERMISSIVE. Add ALLOW rules for legitimate identities (remember that once a waypoint is added, the waypoint identity must also be allowed).
RBAC: access denied (HTTP 403)
Causes: An L7 AuthorizationPolicy on the waypoint or sidecar did not match: the identity, method, or path is wrong, or the caller uses the wrong ServiceAccount.
kubectl -n shop get authorizationpolicy api-l7 -o yaml kubectl -n shop logs deploy/waypoint --tail=30
HTTPRoute weights have no effect / Accepted=False in status
Causes: No waypoint exists, or the namespace / Service lacks istio.io/use-waypoint; the parentRef port does not match; or the backendRef points to a Service that does not exist.
istioctl waypoint list -n shop
istioctl ztunnel-config workloads | grep shop # WAYPOINT column should not be None
kubectl -n shop get httproute api -o jsonpath='{range .status.parents[*].conditions[*]}{.type}={.status} {.reason}: {.message}{"\n"}{end}'
istioctl analyze -n shopistioctl install hangs / istio-cni-node in CrashLoopBackOff
Causes: Insufficient node resources; the CNI config directory does not match the platform (some managed platforms need --set values.cni.cniConfDir=…; see the platform prerequisites on istio.io); or a conflict with another chained CNI plugin.
kubectl -n istio-system describe pod -l k8s-app=istio-cni-node | sed -n '/Events/,$p' kubectl -n istio-system logs -l k8s-app=istio-cni-node --tail=50 istioctl x precheck
1. Write a PeerAuthentication that enables STRICT only for the shop namespace.
Reference answer
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata: { name: default, namespace: shop }
spec:
mtls: { mode: STRICT }If you place it in istio-system (the root namespace), it applies to the whole mesh.
2. Change the HTTPRoute api so that “all requests with header x-canary: true go to v2, and all other requests go to v1.”
Reference answer
spec:
parentRefs: [{ group: "", kind: Service, name: api, port: 9898 }]
rules:
- matches:
- headers: [{ name: x-canary, value: "true" }]
backendRefs: [{ name: api-v2, port: 9898 }]
- backendRefs: [{ name: api-v1, port: 9898 }]Scenario analysis: After a waypoint was added, all the originally normal web → api calls were reset. Removing the waypoint restores them. Why? How do you fix this while keeping the waypoint?
Reference answer
After traffic passes through the waypoint, the destination ztunnel sees the source identity as the waypoint's ServiceAccount (cluster.local/ns/shop/sa/waypoint). The L4 policy allows only web, so the request is denied. Fix: change the L4 policy to allow the waypoint identity, and move the “only web” constraint to the L7 policy on the waypoint (targetRefs pointing to the api Service). This keeps identity-based authorization and also prevents bypassing the waypoint to connect directly to Pods.
Lecture video (title and channel verified via YouTube oEmbed, 2026-11-18)
No verified hands-on video based on Istio 1.3x ambient was found.
Official docs
- Ambient · Getting Started
- Secure and visualize the application
- Enforce authorization policies
- Manage traffic
- Supported releases
Video storyboard
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: An ambient install has only three parts: the control plane, a CNI node agent, and one ztunnel per node.
Narration: Joining the mesh gives you mTLS immediately, and STRICT closes the plaintext back door.
Narration: All the L7 capabilities live in the waypoint: canary releases, method-based authorization, and RBAC access denied responses when requests are rejected.
Narration: Use metrics to decide whether to continue the canary, and you can always set the weights back.
Module 8 · Extending Reviews, Troubleshooting and Self-Check
- For CRDs, Operators, webhooks, and mesh components, state what breaks and what keeps working when each one goes down.
- Uninstall an extension safely in the order “CR → controller / webhook → CRD,” and handle stuck finalizers and namespaces.
- Use one troubleshooting decision tree to locate every common failure in this lesson.
- Use a review checklist to evaluate a request to roll out a new extension.
What: Failure modes of extension components
| Component down | What breaks | What keeps working | Mitigation |
|---|---|---|---|
| Operator controller | New or changed CRs have no effect; deleting a CR with a finalizer gets stuck; status stops updating | Child resources already created keep running (Deployments, database Pods) | 2 replicas + leader election; alerts on reconcile error rate and queue depth |
| Admission webhook (failurePolicy: Fail) | All writes for matching resources fail (this can include Pod creation, so scaling and self-healing all fail) | Read requests and running Pods | Use VAP / CRD CEL where possible instead of a webhook; exclude system namespaces with namespaceSelector; multiple replicas + PDB; a small timeoutSeconds |
| conversion webhook | Reads, writes, list, and watch fail for non-storage versions; controllers and GitOps tools using old versions go blind | Clients accessing the storage version | Controllers use the storage version; webhooks are highly available; certificates rotate automatically |
| Aggregated API backend | Requests for that group; discovery warnings, which can slow namespace deletion and some tools | Other APIs | Delete the APIService when it is not in use; monitor its Available condition |
| istiod | New configuration is not delivered; new workloads cannot get certificates; certificates cannot be renewed after they expire | Existing connections and already-delivered configuration keep working (for a short time) | istiod with multiple replicas + HPA; certificate expiry monitoring |
| The ztunnel / istio-cni on a node | Mesh traffic for enrolled Pods on that node | Other nodes | DaemonSet rolling-update strategy; node-level alerts |
| waypoint | All L7 traffic passing through this waypoint | Traffic that uses only L4 | Waypoint with multiple replicas + PDB (it is an ordinary Deployment) |
Why: Extensions are “cluster dependencies,” not “application dependencies”
When one application goes down, only it is affected. When a webhook, CRD, or mesh component goes down, every team may be unable to deploy. For this reason, the bar for rolling out an extension should be higher than for an ordinary application: a review, an SLO, alerts, a runbook, and an uninstall plan are all required.
How: The safe uninstall order
- Back up the CRs:
kubectl get <crd> -A -o yaml > backup.yaml(Velero can also back up CRs; see hour 4 M7). - Delete the CRs and wait for the controller to run finalizer cleanup (a database Operator may delete PVCs, so confirm the retention policy first).
- Delete the webhook configuration (so that a webhook does not point to a Service that no longer exists after the controller is removed), then delete the controller Deployment and its RBAC.
- Delete the CRD (this deletes all remaining CRs).
- Mesh: First delete the HTTPRoute / AuthorizationPolicy / PeerAuthentication → delete the waypoint → remove the namespace label (sidecar mode also requires restarting Pods) → uninstall Istio.
When: Rollout review checklist (summary)
- CRD: structural schema, CEL validation, status subresource, version plan, object size limit.
- Controller: idempotent, finalizers with timeouts and alerts, leader election, least-privilege RBAC, resource requests / limits, cache scope.
- Webhook: whether a VAP can replace it, failurePolicy, namespaceSelector, replicas and PDB, certificate rotation.
- Mesh: inventory plaintext callers before STRICT; one SA per service; waypoint scope; upgrade and rollback plan.
- Operations: SLO, alerts, runbook, uninstall steps, owner.
kubectl patch to remove the finalizer, and the Terminating state is resolved.” This only skips the cleanup, so external resources may leak. Confirm first. ② “Deleting the Operator's Deployment uninstalls it cleanly.” The webhook configuration, CRDs, CRs, and ClusterRoles all remain, and the webhook can even block writes. ③ “If istiod goes down, mesh traffic stops immediately.” Existing configuration and certificates keep working until they expire, but this is a countdown that needs immediate attention.Blast radius of extension components
Uninstall order
Interactive: fault-injection simulator
Choose a fault to see how it affects “reads / writes / running workloads / mesh traffic,” along with the first diagnostic command. Behavior is based on the kubernetes.io and istio.io documentation.
Command table
| Command | Purpose |
|---|---|
kubectl get <plural>.<group> -A -o yaml > backup.yaml | Back up CRs before uninstalling |
kubectl get ns <ns> -o jsonpath='{.status.conditions}' | Find out why a namespace is stuck in Terminating |
kubectl get <kind> -A -o jsonpath='{range .items[?(@.metadata.deletionTimestamp)]}{.metadata.namespace}/{.metadata.name}{"\n"}{end}' | List objects being deleted (stuck) |
kubectl get validatingwebhookconfigurations -o custom-columns=…failurePolicy… | Audit webhook failure policies |
kubectl get apiservices | grep False | Find unavailable aggregated APIs |
istioctl analyze -A, istioctl proxy-status | Mesh configuration checks, proxy sync status |
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp | Cluster-wide warning events |
Extension health check script
#!/usr/bin/env bash
echo "== Unavailable aggregated APIs"; kubectl get apiservices | awk 'NR==1 || $3 != "True"'
echo "== Webhooks with failurePolicy=Fail"
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations \
-o jsonpath='{range .items[*]}{.kind}/{.metadata.name}: {range .webhooks[*]}{.failurePolicy} {end}{"\n"}{end}' | grep Fail
echo "== CRDs not Established"
kubectl get crd -o jsonpath='{range .items[*]}{.metadata.name} {.status.conditions[?(@.type=="Established")].status}{"\n"}{end}' | grep -v ' True$'
echo "== Namespaces stuck in Terminating"; kubectl get ns | grep Terminating
echo "== Mesh"; command -v istioctl >/dev/null && istioctl analyze -A 2>&1 | tail -5
== Unavailable aggregated APIs NAME SERVICE AVAILABLE AGE == Webhooks with failurePolicy=Fail ValidatingWebhookConfiguration/cnpg-validating-webhook-configuration: Fail Fail Fail == CRDs not Established == Namespaces stuck in Terminating == Mesh ✔ No validation issues found when analyzing all namespaces.
Production use: Turn these checks into scheduled jobs or Prometheus alerts (for example, the apiserver's webhook call failure rate and metrics such as apiserver_admission_webhook_rejection_count; confirm metric names for the version you run).
Lab 8: Fault-Injection Drill (about 15 minutes)
kubectl -n shop-operator-system scale deploy shop-operator-controller-manager --replicas=0
kubectl -n shop delete shapp demo --wait=false
kubectl -n shop get shapp demo -o jsonpath='{.metadata.deletionTimestamp}{"\n"}' # If a value is shown: Terminating
kubectl -n shop-operator-system scale deploy shop-operator-controller-manager --replicas=1
kubectl -n shop get shapp demo # After the controller recovers, cleanup completes: NotFoundkubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata: { name: broken-demo }
webhooks:
- name: broken.demo.example.com
admissionReviewVersions: ["v1"]
sideEffects: None
failurePolicy: Fail
timeoutSeconds: 3
clientConfig:
service: { namespace: default, name: does-not-exist, path: /validate }
rules:
- { apiGroups: [""], apiVersions: ["v1"], operations: ["CREATE"], resources: ["configmaps"] }
namespaceSelector:
matchLabels: { kubernetes.io/metadata.name: shop }
EOF
kubectl -n shop create configmap t1 --from-literal=a=b
error: failed to create configmap: Internal error occurred: failed calling webhook "broken.demo.example.com": failed to call webhook: Post "https://does-not-exist.default.svc:443/validate?timeout=3s": service "does-not-exist" not found
Note that namespaceSelector limits the impact to shop. Without it, ConfigMap creation would fail across the whole cluster. Recovery: kubectl delete validatingwebhookconfiguration broken-demo.
kubectl apply -f ~/k8slab/ext/demo.yaml
kubectl -n shop-operator-system scale deploy shop-operator-controller-manager --replicas=0 # Simulates “deleting the controller first”
kubectl delete crd shopapps.shop.example.com --wait=false
kubectl get crd shopapps.shop.example.com -o jsonpath='{.status.conditions[?(@.type=="Terminating")].message}{"\n"}'
The CRD is stuck because its CRs have finalizers. Use the troubleshooting tree to find the fix path: restore the controller (preferred), or remove the CR finalizers after confirming that the registration in shop-registry has been deleted manually.
istioctl waypoint apply again.ext-health.sh produces clean output, and you can explain each fault's “blast radius + first diagnostic command” out loud.make install deploy IMG=shop-operator:dev.Case 1: A webhook broke cluster scaling
Problem: A policy engine's webhook matched all Pod creations. During a node pool upgrade, the node it ran on was drained, leaving the webhook with no available replicas. After that, no Pod could be created, including the webhook's own Pods, and the cluster deadlocked. Approach: Set the webhook's namespaceSelector to exclude its own namespace and kube-system; run 3 replicas + PDB + topology spread; migrate simple rules to VAP.
Case 2: A CRD was deleted by mistake, and hundreds of certificate objects disappeared together
The cleanup script's kubectl delete -f operator.yaml included the CRD, which deleted every Certificate CR. Approach: Manage the CRDs separately from the Operator; add Argo CD's Prune=false sync option to the CRDs; back up CRs regularly.
Case 3: Canary for a mesh upgrade
istiod upgrades use revisions (two control planes run side by side), and namespaces switch over one at a time. Before the ztunnel DaemonSet is upgraded in a rolling fashion, validate it on one node pool first. Watch the error rate in Kiali throughout, and you can roll back to the old revision at any stage.
Extension Troubleshooting Decision Tree
Start from the symptom and choose step by step. Each leaf gives the cause, the diagnostic command, and the fix. It covers the common failures in M1–M7 of this lesson.
Supplement
namespace "shop" is stuck in Terminating: NamespaceFinalizersRemaining / NamespaceDeletionDiscoveryFailure
Cause: The first means objects inside the namespace have finalizers; the second means an aggregated API is unavailable, so the namespace controller cannot list all resource types.
kubectl get ns shop -o jsonpath='{range .status.conditions[*]}{.type}: {.message}{"\n"}{end}'
kubectl get apiservices | grep False
Fix: Restore or delete the unavailable APIService; handle CRs with finalizers (restore their controller).
1. List the names of all validating webhooks whose failurePolicy is Fail.
Reference answer
kubectl get validatingwebhookconfigurations -o jsonpath='{range .items[*]}{range .webhooks[?(@.failurePolicy=="Fail")]}{.name}{"\n"}{end}{end}'2. List every ShopApp in shop that is being deleted (has a deletionTimestamp), along with its finalizers.
Reference answer
kubectl -n shop get shapp -o jsonpath='{range .items[?(@.metadata.deletionTimestamp)]}{.metadata.name} {.metadata.finalizers}{"\n"}{end}'Scenario analysis: On Friday evening, developers report that “all Deployments fail to update,” with errors containing failed calling webhook. What steps do you take as the on-call engineer?
Reference answer
① From the error, identify the webhook name and its Service. Run kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations to find the configuration. ② Check the backend Pods, EndpointSlices, and certificates. ③ If you cannot recover quickly and the impact is large, follow the emergency procedure: temporarily change that webhook's failurePolicy to Ignore, or delete the configuration (record the change and save the original configuration so you can restore it). ④ After the backend recovers, restore the configuration. ⑤ Post-incident review: namespaceSelector, replica count and PDB, whether VAP can replace it, and add alerts.
Lecture video
No verified video specifically about “extension component failures and uninstalls” was found. You can review the videos for M1 and M6, and read the official docs below.
Official docs
- Dynamic Admission Control (with best practices)
- Admission Webhook Good Practices
- Namespaces (deletion and finalizers)
- Istio Diagnostic Tools
Video storyboard
This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.
Narration: The more an extension depends on network calls, the bigger the impact when it fails.
Narration: When a Fail-policy webhook goes down, it blocks every matching write, and it may even be unable to restart itself.
Narration: The uninstall order is: back up, delete CRs, delete webhooks, delete the controller, delete the CRD.
Command cheat sheet
kubectl api-resources --api-group=<group> -o wide kubectl get crd kubectl get apiservices | grep -v Local kubectl get validatingadmissionpolicies kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
kubectl apply --server-side -f crd.yaml
kubectl wait --for=condition=Established crd/<plural>.<group>
kubectl explain <kind>.spec --recursive
kubectl apply --dry-run=server -f cr.yaml
kubectl get crd <name> -o jsonpath='{.status.storedVersions}'
kubectl get <plural> --field-selector spec.tier=backendkubectl scale <kind> <name> --replicas=3
kubectl patch <kind> <name> --subresource=status --type=merge -p '{"status":{…}}'
kubectl get <plural> --watch --output-watch-events
kubectl get <obj> -o jsonpath='{.metadata.ownerReferences}'
kubectl delete <kind> <name> --cascade=foreground|background|orphan
kubectl get lease -Akubebuilder init --domain example.com --repo example.com/shop-operator kubebuilder create api --group shop --version v1alpha1 --kind ShopApp --resource --controller make manifests generate # CRD / RBAC / DeepCopy make install # install the CRD make run # run locally make test # envtest make docker-build IMG=shop-operator:dev kind load docker-image shop-operator:dev --name lab make deploy IMG=shop-operator:dev make undeploy; make uninstall
kubectl apply --server-side -f <operator>.yaml kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa> kubectl get clustercatalogs,clusterextensions # OLM v1 kubectl get subscriptions,csv,installplans -A # OLM v0 kubectl -n shop get cluster shop-db # CloudNativePG
istioctl install --set profile=ambient --skip-confirmation kubectl label ns shop istio.io/dataplane-mode=ambient istioctl waypoint apply -n shop --enroll-namespace --wait istioctl ztunnel-config workloads istioctl ztunnel-config certificates <ztunnel-pod>.istio-system kubectl -n istio-system logs -l app=ztunnel | grep -E "inbound|outbound" istioctl analyze -n shop istioctl dashboard kiali
kubectl get <kind> <name> -o jsonpath='{.metadata.finalizers}'
kubectl patch <kind> <name> --type=merge -p '{"metadata":{"finalizers":null}}'
kubectl get ns <ns> -o jsonpath='{.status.conditions}'Back up CRs → delete CRs (wait for finalizers) → delete webhook configurations → delete controller + RBAC → delete CRD Mesh: HTTPRoute / policies → waypoint → namespace labels → istioctl uninstall --purge
Quick troubleshooting table
| Symptom | Most likely cause | First command |
|---|---|---|
| the server doesn't have a resource type | CRD not installed / not Established | kubectl get crd | grep <name> |
| Invalid value: "string": <CEL message> | Rejected by CRD CEL rule | kubectl explain + read the message |
| strict decoding error: unknown field | Misspelled field / version mismatch | kubectl explain <kind>.spec |
| CR has no status and no subresource | Controller not running / insufficient RBAC | kubectl logs deploy/<controller> |
| CR / namespace stuck in Terminating | Finalizer with no one handling it | kubectl get … -o jsonpath='{.metadata.finalizers}' |
| failed calling webhook | Webhook backend unavailable | kubectl get endpointslices -n <ns> |
| Connection reset by peer (after enrollment) | STRICT or L4 policy denial | kubectl -n istio-system logs -l app=ztunnel |
| HTTP 403 RBAC: access denied | L7 AuthorizationPolicy | kubectl get authorizationpolicy -n <ns> |
| HTTPRoute weights have no effect | No waypoint | istioctl waypoint list -n <ns> |
Recommended config snippet
x-kubernetes-validations:
- rule: "self.minReplicas <= self.maxReplicas"
message: "minReplicas cannot be greater than maxReplicas"
properties:
tier:
type: string
x-kubernetes-validations:
- rule: "self == oldSelf"
message: "tier cannot be changed after creation"failurePolicy: Fail
timeoutSeconds: 3
namespaceSelector:
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: [kube-system, shop-operator-system]Capstone lab + final quiz
The platform team wants application teams to get a “database-backed, encrypted, canary-capable service” by writing a single ShopApp object. You need to: use kubebuilder to deliver ShopApp v1alpha1 (with CEL validation, scale / status subresources, and finalizers) → use CloudNativePG to provide the database → use Istio ambient to provide mTLS, identity-based authorization, and canary releases → run fault drills → uninstall in the correct order.
kubectl get nodes (v1.37), kubebuilder version, istioctl version --remote=false; kubectl -n shop get deploy web api.make deploy IMG=shop-operator:0.1.0; create two CRs: catalog (backend, podinfo, replicas 2) and storefront (frontend, nginx:1.29-alpine, port 80).
kubectl -n shop get shapp -o wide
kubectl -n shop get shapp storefront -o jsonpath='{.status.conditions[?(@.type=="Available")].status}{"\n"}'
Hint: The sample controller passes podinfo arguments to the container, which nginx cannot use. That is the exercise: add a branch for frontend (no args, and the probe path changed to /), redeploy the Operator, and watch the CR converge on its own.
kubectl apply --dry-run=server to verify that all 4 invalid cases (the latest image tag, replicas 30, frontend on port 9898, and changing tier) are rejected.shop-db (3 instances), and delete the primary instance to drill failover.catalog-v2) and use HTTPRoute for a 90/10 split; the L7 policy allows only storefront's SA to call catalog's GET.make undeploy → make uninstall → uninstall CNPG → uninstall the mesh following the M7 cleanup steps → ext-health.sh produces clean output.Open-ended self-check
1. When should you choose an aggregated API instead of a CRD?
When data is computed in real time or is large and should not go into etcd; when you need non-standard verbs or custom storage; or when you need full control over API behavior. The cost is that you must run and keep highly available an apiserver yourself.
2. Why should a controller be level-triggered?
Events can be lost, merged, and delivered out of order, and processes restart. Only by computing the difference between “current desired state” and “current actual state” and acting idempotently can you guarantee eventual consistency.
3. What problem does each of ownerReference and finalizer solve?
ownerReference lets the garbage collector cascade-delete child resources in the same namespace; a finalizer lets the controller clean up resources outside the cluster or in other namespaces before the object is actually deleted.
4. Before installing a third-party Operator, what are the three things you care about most?
Permission scope (especially Secrets and webhooks), the upgrade and CRD evolution strategy, and project health along with an uninstall plan.
5. How do you choose between ambient and sidecar?
For new deployments, prefer ambient: joining needs no restarts, it uses fewer resources, and it adds L7 on demand. Use sidecar when you depend on sidecar-only features or need full L7 capability on every workload; the two can coexist.
6. After a waypoint is added, why must the L4 authorization policy be adjusted?
The destination ztunnel sees the source identity as the waypoint's ServiceAccount. L4 allows only the waypoint, and fine-grained authorization of the calling identity moves to the L7 policy on the waypoint.
Sources and versions
| Topic | Verification result | Source (verified on) |
|---|---|---|
| Kubernetes version | v1.37 is the current latest minor version (released 2026-08-26); ValidatingAdmissionPolicy is GA in v1.30; MutatingAdmissionPolicy is GA in v1.36; Storage Version Migrator (storagemigration.k8s.io/v1) is GA in v1.37 | Course specification (verified 2026-11-15), hour 5 M6 |
| CRD feature status | CEL validation rules have been stable since v1.29; selectableFields has been stable since v1.32 (introduced in v1.30); validation ratcheting and optionalOldSelf have been stable since v1.33 (introduced in v1.28); conversion rules do not participate in ratcheting; CRDs are rejected when CEL cost exceeds the budget | CRD task page (2026-11-18) |
| kubebuilder | v4.16.0 (2026-09-10): controller-runtime v0.24.1 → v0.25.0, k8s.io/* v0.37.0, supports Kubernetes 1.37; v4.15.0 (2026-06-15) upgraded to Go 1.26; the Quick Start requires Go v1.24.6+, install command go.kubebuilder.io/dl/latest/…, make targets install / run / docker-build / deploy / undeploy / uninstall | GitHub Releases · Quick Start (2026-11-18) |
| Istio | 1.32.0 was released on 2026-11-09 and supports Kubernetes 1.33–1.37, with EOL expected around 2027-06; 1.31 (2026-08-27) and 1.30 (2026-05-14, EOL expected 2026-12-16) are still supported | Supported releases · Releases (2026-11-18) |
| Istio ambient commands | istioctl install --set profile=ambient --skip-confirmation; conditional installation of Gateway API CRDs (the docs pin v1.6.1 experimental); istio.io/dataplane-mode=ambient; istioctl waypoint apply --enroll-namespace --wait → istio.io/use-waypoint: waypoint; L4 policies use selector, L7 uses targetRefs; 90/10 example with HTTPRoute parentRef pointing to a Service; addons from release-1.32; ztunnel HBONE port 15008, istioctl ztunnel-config workloads / certificates | Getting started and its subpages, Troubleshoot ztunnel (2026-11-18) |
| Gateway API | v1.7.0 was released on 2026-10-29; v1.6.3 (2026-10-06) is the version pinned for this course (hour 3) | Releases (2026-11-18) |
| OLM v1 | operator-controller v1.12.0 (2026-09-24), install script …/download/v1.12.0/install.sh; ClusterExtension olm.operatorframework.io/v1, spec.namespace + source.catalog.packageName / channels / version; the release notes mention that spec.serviceAccount is deprecated | Releases · Install an extension (2026-11-18) |
| CloudNativePG | v1.30.2 (2026-11-17), install manifest releases/download/v1.30.2/cnpg-1.30.2.yaml | Releases (2026-11-18) |
| Lab environment | kind v0.33.0, node v1.37.0, the shop application, and Gateway API v1.6.3, consistent with the other hours in this course | Course specification · Hour 1 |
Video verification note
The following videos were verified for title and channel through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json, 2026-11-18): TechWorld with Nana, “Kubernetes Operator simply explained in 10 mins” (ha3LjlD6g7g); freeCodeCamp.org, “Kubernetes Operator Best Practices – Kubebuilder Deep Dive” (hAsz5GAbBQE); TechWorld with Nana, “Istio & Service Mesh - simply explained in 15 mins” (16fgzklcF7Y); IBM Technology, “Istio Service Mesh Explained” (6zDrLvpfCK4); HashiCorp, an IBM Company, “What is a service mesh” (vh1YtWjfcyk). Durations and upload dates were not verified. Some videos predate ambient mode and kubebuilder v4; the cards note this.
Voice narration notes
The “Voice” tab reads the narration aloud with the browser's Web Speech API in en-US. Results depend on the speech voices installed on your operating system. The environment that generates this lesson cannot call a TTS service, so no MP3 is embedded.
Known limitations
- None of the commands in this hour were run against a real cluster: the commands and YAML are written based on the official docs listed above; the IPs, UIDs, timestamps, hashes, Pod name suffixes, error message wording, and ratio figures in “expected output” are examples.
- The Go code is written for kubebuilder v4.16 / controller-runtime v0.25 and has not been compiled; the scaffold file contents follow what
kubebuilder initactually generates. - The following could not be fully verified, so they are handled conservatively and marked “refer to the official docs”: the fields of StorageVersionMigration, the parameters of
kubebuilder create webhook --conversion, the default PostgreSQL image version and Pod role label name for CNPG, the exact permissions of the CNPG controller, the packaging format restrictions and serviceAccount changes in OLM v1, port-level mTLS and probe handling in ambient, the default certificate validity period for istiod, the resource usage figures for sidecars and ztunnel, and the apiserver webhook metric names. - The mesh resource comparison is a classroom estimate; check against measurements in your own environment. Numbers in the animation are illustrative.
- Hour 9 (optional) is being written in parallel with this hour, so cross-hour references follow the final content of each hour.