Kubernetes Hour 8: Extending Kubernetes — CRDs, Operators and Service Mesh

For the first 7 hours, we have been “using” Kubernetes’ built-in APIs. This hour shows how to extend them: custom resources (CRDs), controllers you write yourself (Operators), and the service mesh that moves networking down into the infrastructure layer (Istio ambient / sidecar)
Kubernetes v1.37kubebuilder v4.16.0controller-runtime v0.25.0Istio 1.32.0CloudNativePG 1.30.2CRD · CEL · Operator · ambient meshVerified against official docs · 2026-11-18
Where this hour fits in the coursePrerequisites: hours 1–7 (especially hour 1’s “Declarative model and control loop”, hour 3 Gateway API, hour 5 Admission control: VAP · MAP · Webhook, and hour 6 Helm / Kustomize / GitOps). It is followed by Hour 9 (optional): 50 production problems + 50 interview questions. All labs in this hour run on the kind cluster lab built in hour 1, with no cloud costs.
Overall learning goals
  • 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 / deploy end 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

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: kind cluster and extension toolskind 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
100–06API extension overviewCRDs, aggregated APIs (APIService), admission webhooks and VAP / MAP, controllers; selection decisionsAll extension points a request passes through (CRD request vs. aggregated API request)Survey the extension points in the lab cluster
206–13CRD deep divestructural schema, pruning, defaults, CEL rules and oldSelf, ratcheting, status / scale subresources, printer columns, multiple versions and conversionCRD write validation pipelineHand-write the ShopApp CRD and trigger each validation rule
313–21Controller patternlist-watch, informers, workqueue, level-triggered, idempotency, ownerReferences, finalizers, leader electionReconcile loop (normal / retry on failure / finalizer deletion)Build a “poor man’s” controller by hand with kubectl + bash
421–28Operator in practice (kubebuilder)kubebuilder init / create api, markers, Reconcile, CreateOrUpdate, status conditions, RBAC, envtestmarker → controller-gen → manifests → managerShopApp Operator: make run and make deploy
528–35Using existing OperatorsOperatorHub, capability levels, OLM v0 / v1 (ClusterExtension), Helm installation, CRD upgrades and permission risks, review checklistOperator selection scorerInstall CloudNativePG and create a 3-instance PostgreSQL
635–42Service mesh basicsWhy you need a mesh; sidecar vs. ambient (ztunnel / waypoint / HBONE); mTLS and SPIFFE identity; GAMMA; when not to use a meshAn mTLS path through ztunnel / waypoint / sidecarReading exercise: write a data-plane selection ADR for shop
742–50Istio in practiceambient installation, namespace enrollment, PeerAuthentication STRICT, AuthorizationPolicy (L4 / L7), waypoint, HTTPRoute weights, Kiali / PrometheusCanary weights + mTLS simulatorshop api v1/v2 90/10 canary
850–60Extension review, troubleshooting and self-checkCommon CRD / Operator / mesh failures, production review checklist, uninstall orderFault injection simulator + extension troubleshooting decision treeFault injection drill
—After classCheat sheet · Capstone labShopApp v1alpha1 → CEL → Operator → finalizer → CNPG database → ambient mTLS → canary → cleanupFinal quiz: 12 questionsAcceptance checklist: 12 items

Knowledge coverage matrix

Target skillModuleKey commands / objectsLabProduction case
Choose the right API extension pointM1kubectl api-resources, kubectl get apiservices, kubectl get crd, kubectl get validatingadmissionpolicies✓✓
Write and evolve CRDsM2openAPIV3Schema, x-kubernetes-validations, subresources, additionalPrinterColumns, kubectl explain✓✓
CRD multiple versions and storage versionM2spec.conversion, status.storedVersions, StorageVersionMigrationReading✓
Controller mechanicsM3kubectl get --watch --output-watch-events, kubectl get lease -n kube-system, ownerReferences, finalizers✓✓
Write an Operator with kubebuilderM4kubebuilder init / create api, make manifests install run deploy, kind load docker-image✓✓
Select and operate third-party OperatorsM5kubectl apply --server-side -f cnpg-1.30.2.yaml, ClusterExtension, kubectl auth can-i --as✓✓
Understand the mesh data planeM6istio.io/dataplane-mode=ambient, istio-injection=enabled, HBONE 15008Reading✓
Istio security and trafficM7istioctl install --set profile=ambient, istioctl waypoint apply, PeerAuthentication, AuthorizationPolicy, HTTPRoute✓✓
Mesh observabilityM7istioctl ztunnel-config workloads, istioctl dashboard kiali, istio_requests_total✓✓
Extension troubleshooting and reviewM8kubectl get events, kubectl patch … finalizers, istioctl analyze✓✓
End-to-end integrationCapstone labAll✓✓

Topics excluded from this hour

TopicReasonWhere to learn it
Full writing of ValidatingAdmissionPolicy / MutatingAdmissionPolicy and admission webhooksCovered in hour 5; this hour only references it when selecting toolsHour 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 CRDsThe delivery toolchain is covered in hour 6 and in the Helm / Argo CD coursesHour 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 hourkubernetes/sample-apiserver
Istio multicluster, egress gateways, Wasm extensions, hands-on Linkerd / Cilium meshBeyond 1 houristio.io docs “Multicluster”; official docs of each project
Dashboard and alert design for mesh metricsBelongs in the observability coursePrometheus & Grafana course

How to use this material

10 pages per module
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.
Learning progress
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).
One main thread
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.
Version notesThis hour is based on Kubernetes v1.37 (upstream release on 2026-08-26). Tool versions were verified on 2026-11-18: kubebuilder v4.16.0 (2026-09-10, controller-runtime v0.25.0, k8s.io/* v0.37.0), Istio 1.32.0 (2026-11-09, supports Kubernetes 1.33–1.37), Gateway API v1.7.0 was released on 2026-10-29 (this course pins v1.6.x throughout), OLM v1 operator-controller v1.12.0 (2026-09-24), CloudNativePG v1.30.2 (2026-11-17). CRD-related features: CEL validation rules GA in v1.29, selectableFields GA in v1.32, validation ratcheting and 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)

Back to the local kind cluster: this hour does not need a cloud account, but it does need the Go toolchain (to write the Operator) and istioctl (to install the mesh)
Before class ≈ 20 minkind v0.33.0 · kubectl 1.37 · Go 1.26 · kubebuilder 4.16.0 · istioctl 1.32.0
Prerequisites
  • Completed hours 1–7; familiar with the shop application (namespace shop: web = nginx:1.29-alpine, api = ghcr.io/stefanprodan/podinfo:6.17.0 on 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 earlierHow it is used in this hour
Hour 1: control loop, the full journey of kubectl applyA 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 controlOperator permission reviews (M4, M5); choosing between webhooks and VAP (M1); mesh identity is based on ServiceAccount (M6)
Hour 3: Service, Gateway APIMesh east-west routing attaches HTTPRoute to a Service (GAMMA, M6–M7)
Hour 6: Helm, GitOps, observabilityDelivery order for Operators and CRDs; Prometheus scrapes mesh metrics (M5, M7)
Hour 7: EKSThe 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
Resource warningIstio ambient (istiod + istio-cni + one ztunnel per node) plus Kiali / Prometheus needs roughly 1.5–2 GiB of extra memory on a 3-node kind cluster. If the lab machine has only 8 GiB, run 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
Self-check list

Module 1 · API extension overview: CRDs, aggregated APIs and admission

00:00 – 06:00 · Kubernetes “extensibility” shows up as a few fixed slots in the apiserver pipeline: adding new resource types, proxying to another API service, intercepting and rewriting requests, and running controllers outside the API
6 minCRD apiextensions.k8s.io/v1 · APIService apiregistration.k8s.io/v1 · VAP v1.30 GA · MAP v1.36 GA★★★★☆ Choosing the wrong extension point means a long-term operational burden
Learning objectives
  • 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.
Prerequisites: hour 1 M5 (the full journey of apply), hour 5 M6 (admission control). Importance: ★★★★☆

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 pointWhat it extendsWhere data is storedWho implements the logicTypical 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 controllercert-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 serverDecided by your service (it can store nothing and compute on demand)An extension apiserver you write yourselfmetrics-server (metrics.k8s.io), custom metrics adapters
AdmissionAdds no resources; instead, rewrites or rejects requests before they are writtenStores no dataA webhook service, or a ValidatingAdmissionPolicy / MutatingAdmissionPolicy that runs CEL inside the apiserverKyverno, 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 stateReads and writes objects through the APIA process running inside (or outside) the cluster that list-watches the apiserverThe 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 explain and 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 ShopApp object, so application teams write only about 10 lines of YAML.

How: the path of a write request inside the apiserver

  1. 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"].
  2. kube-aggregator checks the path. If an APIService points 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.
  3. Mutating admission: built-in plugins → MutatingAdmissionPolicy (CEL, GA in v1.36) → MutatingAdmissionWebhook.
  4. Object schema validation: built-in types are validated by Go code; CRDs are validated by the OpenAPI v3 schema plus x-kubernetes-validations (CEL).
  5. Validating admission: ValidatingAdmissionPolicy (CEL, GA in v1.30) and ValidatingAdmissionWebhook are called in parallel.
  6. Persisted to etcd → watch notifies all controllers → controllers reconcile.

When: how to choose

NeedPreferredWhy not the others
A new kind of “declarative object” that the system should act on automatically (such as ShopApp, database clusters, certificates)CRD + controllerAn 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 APIEvery 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 backendAggregated APICRDs 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 forbiddenVAP (CEL); add a webhook only for complex logic or external dataA 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 CRDNo 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
Common misconceptions ① “Once the CRD is installed, the feature works.” A CRD only lets the apiserver store this kind of object. Without a controller, nothing happens after 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

kubectlPOST /apis/… Authentication · authorizationRBAC (including CRDs) kube-aggregatorRoutes by group/version Mutating admissionMAP (CEL)Mutating webhook Schema validationOpenAPI v3CRD CEL rules Validating admissionVAP (CEL)Validating webhook etcdPersistence extension apiservere.g. metrics-serverIts own authentication proxy / storage APIService match → proxy apiextensions-apiserverDynamically generates a REST handler for each CRDpruning · defaulting · version conversion Webhook service (Pod in the cluster)AdmissionReview / ConversionReviewHTTPS · failurePolicy · timeout Controller (outside the API): list-watch → informer cache → workqueue → reconcile → write back to the subresource / status that the spec points to Built-in controllers in kube-controller-manager · your Operator (Deployment) · Argo CD · Karpenter · cert-manager Like kubectl, they are just API clients: they also go through authentication, authorization and admission CRDs let the API “store” objects; controllers make them “take effect” watch events
Figure 1-1: the write-request pipeline. Aggregated APIs branch off at the routing stage. Admission rewrites or rejects before persistence. CRD validation sits between the two admission stages. Controllers work after etcd, through watch.

Extension method decision diagram

Do you need a new object type? No: you only want to constrain or rewrite existing objectsSimple rules → VAP / MAP; complex rules → webhook Yes: does the data need to be persisted in etcd?Low frequency, declarative, ≤ 1.5 MiB per object Yes → CRD + controller90% of cases (Operators) No → aggregated APIOn-demand computation / custom storage Do you need to keep correcting drift after a write?Yes → add a controller without a CRD (watching built-in resources)
Figure 1-2: first ask “Do we need a new type?”, then “Does it need to go into etcd?”. Put validation rules in the CRD itself or in VAP first, and consider a webhook last.

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.

kubectl Authentication / authorizationRBAC aggregatorAPIService routing Mutating admissionMAP / webhook schema + CELapiextensions Validating admissionVAP / webhook etcd metrics-serverextension apiserver ShopApp controller (Operator)watch event → reconcile
Ready. Click “Play.”
$ kubectl apply -f shopapp.yaml

Command table

CommandPurposeKey parameters / notes
kubectl api-resourcesList all resource types (built-in, CRD and aggregated)--api-group=shop.example.com, -o wide (shows verbs)
kubectl api-versionsList all group/versionsAppears right after the CRD is installed
kubectl get crdList CRDs-o custom-columns to view group, scope and versions
kubectl get apiservicesList APIServices (including the built-in Local ones and external services behind aggregation)When AVAILABLE is False, check MESSAGE
kubectl get validatingadmissionpolicies,validatingadmissionpolicybindingsCEL admission policyHour 5 M6
kubectl get mutatingwebhookconfigurations,validatingwebhookconfigurationsAdmission webhookCheck failurePolicy and namespaceSelector
kubectl get --raw /apis/<group>/<version>Read the discovery document directlyTroubleshoot “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)

Goal: count how many CRDs, aggregated APIs, admission policies and webhooks the cluster has, and experience firsthand that “a CRD only stores data and does nothing.” Environment: kind cluster lab.
Count resource kinds
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.

Find the aggregated APIs and the Services behind them
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)"
Create the Note CRD and an object: run item 4 on the “Commands” page, then try writing a text longer than 200 characters and observe the schema validation error:
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
RBAC view: CRD resources are controlled by RBAC just like built-in resources.
kubectl auth can-i list notes.demo.example.com -n shop --as=system:serviceaccount:shop:default
no
Verify: 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.
Cleanup: 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.

Command-line exercises

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)

▶
Kubernetes Operator simply explained in 10 mins — TechWorld with Nana
English · duration and upload date not verified · Purpose: an introduction to the relationship between CRDs, controllers and Operators

Official docs

Video storyboard script

This course material cannot generate the video or MP3 directly, so the storyboard and narration script are provided.

Shot 1 · 0:00–0:20
Visual: a horizontal pipeline. Authentication, authorization, aggregated routing, mutating admission, validation, validating admission and etcd light up in turn.
Narration: every write request passes through this pipeline, and extension points plug into a few fixed positions along it.
Shot 2 · 0:20–0:45
Visual: a new ShopApp-shaped block is placed into etcd, with the label “CRD: stores, but does nothing.”
Narration: a CRD teaches the API to store a new kind of object, but it is the controller that makes it take effect.
Shot 3 · 0:45–1:05
Visual: a request turns at the aggregated route and enters metrics-server.
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.
Shot 4 · 1:05–1:30
Visual: a decision tree. Do we need a new type? Do we need persistence? Is it only validation? The three outcomes are CRD plus controller, aggregated API, and VAP.
Narration: nine out of ten cases are CRD plus controller. For validation alone, use CEL and do not rush to write a webhook.
Or score ≥ 70% on the quiz

Module 2 · CRD deep dive: schema, versions, CEL validation and the status subresource

06:00 – 13:00 · A CRD is an API contract: field types, defaults, constraints, status and version evolution, all written in openAPIV3Schema
7 minapiextensions.k8s.io/v1 · CEL rules GA in v1.29 · ratcheting GA in v1.33 · selectableFields GA in v1.32★★★★★ Once an API is published, it must stay compatible for a long time
Learning objectives
  • Write an openAPIV3Schema that meets the structural schema requirements, and understand pruning (dropping unknown fields) and default.
  • 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.
Prerequisites: M1; hour 1 M3 (the API object model: spec / status, metadata.generation). Importance: ★★★★★

What: the parts of a CRD

FieldMeaningNotes
spec.group / names / scopeAPI group, plural / singular / Kind / short name, Namespaced or Clustermetadata.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.openAPIV3SchemaOpenAPI 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-validationsCEL rules: rule, message / messageExpression, reason, fieldPath, optionalOldSelfGA in v1.29. A rule that references oldSelf is a “transition rule” and only runs on updates.
subresources.statusEnable /status: updates to the main resource ignore status, and updates to /status ignore changes outside specOnce enabled, only spec changes increment metadata.generation
subresources.scaleEnable /scale: specReplicasPath, statusReplicasPath, labelSelectorPathAfter that you can run kubectl scale, and HPA can act directly on this CR
additionalPrinterColumnsColumns for kubectl get: name, type, jsonPath, prioritytype can be integer / number / string / boolean / date
selectableFieldsAllows --field-selector on these fieldsGA in v1.32; up to 8 per version
conversionNone (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: description appears in kubectl explain and 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.
Common misconceptions ① “Putting 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

CustomResourceDefinition name: shopapps.shop.example.comgroup: shop.example.comnames: ShopApp / shopapps / shappscope: Namespaced versions[v1alpha1]served: true · storage: trueschema.openAPIV3Schemasubresources: status · scaleadditionalPrinterColumns ×4selectableFields: .spec.tierconversion: None (single version) spec (user intent) image string requiredCEL: tag present and not latest replicas int 0–20 default 2 port int 1–65535 default 9898 message string maxLength 100 tier enum frontend|backendCEL transition rule: self == oldSelf Object-level CEL:When tier == 'frontend', port must be 80 or 8080 Unknown field → strict error / pruning status (written by the controller) replicas intreadyReplicas intselector string (used by scale)url stringobservedGeneration intconditions[]Available / Progressing / Degraded Can only be written through the /status subresourceRBAC: shopapps/statusspec changes → generation+1
Figure 2-1: a CRD = metadata + the schema and subresources for each version. spec is written by the user, and status is written by the controller.

Multiple versions and storage version migration

Stage 1v1alpha1 served+storagestoredVersions=[v1alpha1] Stage 2: add v1Two versions served, v1 is storageConversion webhook goes live Stage 3: migrateRewrite all objects as v1StorageVersionMigration Stage 4: retirestoredVersions=[v1]v1alpha1 served:false → delete Read request GET /apis/shop.example.com/v1alpha1/…: fetch the v1 object from etcd → ConversionReview(desiredAPIVersion=v1alpha1) → webhook returns → default → response Watch also converts. When the webhook is slow or down, all list and watch calls from older-version clients (including older controllers) fail. So the conversion webhook is a component that must be highly available, and conversion must round-trip without loss (v1 → v1alpha1 → v1 must not drop fields; annotations are commonly used to store new fields)
Figure 2-2: the four stages of version evolution. Before retiring an old version, confirm that it is no longer in storedVersions.

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.

DecodeStrict field validation Version conversionNone / Webhook pruning+ default Mutating admissionMAP / webhook OpenAPI validationtype/min/enum CEL rulesself / oldSelf Validating admission → etcdStorage version 422 Invalid → kubectl prints the errorThe object did not enter etcd, so the controller sees no events
Ready. Click “Play.”
$ kubectl apply -f shopapp-demo.yaml

Command table

CommandPurposeKey parameters
kubectl apply --server-side -f crd.yamlInstall 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 --recursiveView 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 usedMust check before retiring a version
kubectl scale shopapp demo --replicas=3Scale through the scale subresourceRequires 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=backendFilter by selectableFieldsv1.32 GA
kubectl apply --dry-run=server -f cr.yamlServer-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)

Goal: get hands-on experience with defaults, pruning and strict field validation, OpenAPI constraints, cross-field CEL rules, conversion rules, the scale and status subresources, and printer columns. Environment: kind lab, namespace shop.
Install the CRD: save the YAML from section 1 of the Commands tab as ~/k8slab/ext/shopapp-crd.yaml, then run kubectl apply --server-side -f shopapp-crd.yaml and kubectl wait.
Create a valid object and check the defaults: run demo.yaml from section 2 of the Commands tab, and confirm that replicas=2 and port=9898 are filled in.
Trigger four kinds of errors: run the four commands in turn (the latest image, replicas=50, changing tier, and a misspelled field). Match each error message to the mechanism it describes on the How it works tab. Then try one cross-field rule:
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.

Pruning without strict validation:
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.

scale / status / selectableFields: run section 3 of the Commands tab. Then run kubectl -n shop get shopapps --field-selector spec.tier=frontend. It should return only storefront.
Verify: kubectl -n shop get shopapps -o wide shows the Tier column. kubectl get shop -n shop (categories) lists all ShopApps.
Clean up: 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.

Command-line exercises

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: .message

Check 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.yaml

Scenario 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)

▶
Kubernetes Operator Best Practices – Kubebuilder Deep Dive — freeCodeCamp.org
English · duration and upload date not verified · Purpose: generating the CRD schema, validation, and subresources with kubebuilder markers

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

Video storyboard

This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: a split screen of ShopApp YAML. On the left, the CRD schema. On the right, one CR. Lines connect matching fields.
Narration: a CRD is an API contract. Each field's type, range, and default value are written in the schema.
Shot 2 · 0:25–0:55
Visual: the CR passes through five gates in order: decoding, pruning, defaulting, OpenAPI validation, and CEL. It is rejected at the CEL gate because of the latest image.
Narration: an invalid object is rejected before it reaches etcd. The controller never sees it.
Shot 3 · 0:55–1:20
Visual: a lock on the tier field, with "self == oldSelf" written beside it.
Narration: a rule that references oldSelf only runs on updates. It is often used to make a field immutable.
Shot 4 · 1:20–1:50
Visual: a timeline with four stages: add v1, switch storage, migrate, and clean up storedVersions.
Narration: before you retire an old version, first confirm that it is no longer listed in storedVersions.
or score 70% or higher on the quiz

Module 3 · Controller Patterns: Informers, Reconcile, and Finalizers

13:00 – 21:00 · Every controller (built-in, custom, or an Operator) follows the same skeleton: list-watch → local cache → deduplicating queue → idempotent reconcile → write status back
8 minclient-go informer · controller-runtime v0.25 · coordination.k8s.io/v1 Lease★★★★★ Getting controllers right comes down to idempotency and state-driven logic
Learning objectives
  • 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.
Prerequisites: hour 1 M1 (declarative model and control loops) and M2 (CRDs and subresources). Importance: ★★★★★

What: The Five Parts of a Controller

ComponentResponsibilityKey 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 → workqueuePut 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.
ReconcileRead 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 backoffIf 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 with sleep inside 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.
Common misconceptions ① "The controller handles every event it receives." The queue merges multiple events for the same key. ② "A resync re-LISTs everything from the apiserver." An informer resync only requeues the objects in the cache. It does not call the apiserver. ③ "ownerReference can span namespaces." It cannot. The GC treats a cross-namespace owner as missing, so child resources may be deleted by mistake. ④ "More finalizers means more safety." Each finalizer is a place where deletion can get stuck. If you uninstall a controller without removing its finalizers, the CR and the namespace both stay in Terminating.

Informer and workqueue structure

kube-apiserveretcdLIST + WATCH Shared informer (one per type) ReflectorLIST rv=1200WATCH from 1200410 → LIST again DeltaFIFOAdded / UpdatedDeleted / Sync Indexer (local cache)By namespace / custom indexclient.Get / List read from hereEventually consistent (may be slightly stale) Workqueue (rate-limited)key: shop/demo (deduplicated)Failure → AddRateLimited backoffRequeueAfter → AddAfter Reconcile worker ×NRead cache → diff → write APISame key is not processed concurrentlyRuns only on the Lease holder Event handler: enqueue key Write: Create / Update / Patch / Status Child resource informerDeployment / ServiceChange → find ownerRef→ enqueue the owner's key
Figure 3-1: reads go to the local cache, and writes go to the apiserver. Events only signal which key needs a look. The actual decision is made in reconcile, based on the current state.

Deletion flow: finalizers and garbage collection

kubectl deleteshopapp demo Has finalizerOnly sets deletionTimestampState: Terminating Controller reconcileClean up resources outside the cluster or in other namespacesFailure → backoff and retry Remove finalizerUpdate metadatafinalizers is empty apiserver deletes the objectGC follows ownerReferenceDelete Deployment / Service Controller uninstalled / no permission / cleanup keeps failing → object stays Terminating foreverCR stuck → namespace deletion stuck → CRD deletion stuck (M8 troubleshooting)
Figure 3-2: a finalizer turns deletion into two phases: mark and clean up first, then actually delete. ownerReference handles cascade deletion of child resources inside the cluster.

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.

apiserveretcd informerwatch event → cache workqueueEmpty Reconcile()Desired vs actual DeploymentService (ownerRef) statusconditions Resource outside the clusterRegistration / DNS
Ready. Click Play.
$ kubectl apply -f demo.yaml

Command table

CommandPurposeKey options
kubectl get shopapps -n shop --watch --output-watch-eventsSee the event stream from the controller's point of viewEVENT 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 ownercontroller: true marks the managing owner
kubectl delete shopapp demo --cascade=foregroundForeground 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-systemCheck the leader election lockholderIdentity, renewTime
kubectl get events -n shop --field-selector involvedObject.kind=ShopAppEvents 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)

Goal: without writing any Go, use about 50 lines of bash to implement LIST → WATCH → idempotent reconcile → ownerReference → write status. See level-triggered behavior and self-healing for yourself, then manually demonstrate a finalizer. Environment: the ShopApp CRD and demo object from M2. Note: this is a teaching script. It does not handle concurrency, backoff, or leader election. Those are exactly why M4 uses controller-runtime.
Write the script
#!/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.

Run (terminal A): 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
Self-healing and level-triggered behavior (terminal B):
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."

Two-phase deletion with a finalizer (the script keeps running):
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.

Verify: you can point to the line in the script that corresponds to the Reflector's LIST, the line for WATCH, where idempotency shows up, and where the status subresource shows up. You can also name the 4 things it is missing: a cache, a deduplicating queue, backoff, and leader election.
Clean up: stop the script with Ctrl+C. Recreate demo with 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.

Command-line exercises

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 reference

Scenario 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)

▶
Kubernetes Operator simply explained in 10 mins — TechWorld with Nana
English · duration and upload date not verified · Purpose: an intuitive explanation of control loops and Operators
▶
Kubernetes Operator Best Practices – Kubebuilder Deep Dive — freeCodeCamp.org
English · duration and upload date not verified · Purpose: best practices for reconcile, idempotency, and finalizers

Official docs

Video storyboard

This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: a thermostat set to 22 degrees, with the room at 19 degrees and the heat on. When the room reaches 22 degrees, the heat turns off.
Narration: a controller is like a thermostat. It does not care what happened. It only compares the desired state with the actual state.
Shot 2 · 0:25–0:55
Visual: the apiserver sends a stream of events. The informer writes them to the cache. Three identical keys merge into one entry in the queue.
Narration: an event only reminds you which object needs a look. The queue merges duplicate reminders automatically.
Shot 3 · 0:55–1:25
Visual: reconcile fails to create a Deployment. The key returns to the queue with longer and longer waits, and succeeds on the third try.
Narration: when something fails, return an error and let the queue retry with exponential backoff. Every step must be idempotent.
Shot 4 · 1:25–1:55
Visual: after kubectl delete, the object turns gray (Terminating). The controller cleans up the external DNS record and then removes the finalizer tag. The object and its child resources disappear together.
Narration: a finalizer makes deletion a two-phase process. ownerReference makes child resources follow automatically.
or score 70% or higher on the quiz

Module 4 · Operator in Practice: Write an Operator with kubebuilder

21:00 – 28:00 · Hand the M2 CRD and the M3 control loop over to the framework. kubebuilder generates the project skeleton, and controller-runtime provides the informer, workqueue, and leader election. You only write Reconcile.
7 minkubebuilder v4.16.0 · controller-runtime v0.25.0 · Go 1.26★★★★☆ A must-have skill for platform teams
Learning objectives
  • Use kubebuilder init and create api to generate a project. Explain the role of api/, internal/controller/, cmd/main.go, and config/.
  • Use markers to declare validation, defaults, subresources, printer columns, and RBAC. Use make manifests to 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 with make docker-build, kind load, and make deploy. Read the logs, the Lease, and RBAC.
Prerequisites: M2 and M3, and basic Go syntax (structs, pointers, error returns). Importance: ★★★★☆

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 / fileContentsDo you edit it?
api/v1alpha1/shopapp_types.goSpec / Status Go structs + markers✓ Define the API
api/v1alpha1/zz_generated.deepcopy.goDeepCopy methods (make generate)✗ Auto-generated
internal/controller/shopapp_controller.goReconcile, SetupWithManager, RBAC markers✓ Business logic
internal/controller/*_test.go, suite_test.goTests based on envtest (real apiserver and etcd binaries)✓ Write tests
cmd/main.goCreate the Manager, register controllers, --leader-elect, metrics and probesFew
config/crd/bases/, config/rbac/role.yamlGenerated by make manifests✗ Do not edit by hand
config/default/, config/manager/, config/samples/Kustomize overlays for deployment, and sample CRsAs 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

  1. Get the primary object (from the cache). If NotFound, return nil (it was deleted, and child resources are left to GC).
  2. Deletion branch: if DeletionTimestamp is set, clean up external resources, remove the finalizer, and return.
  3. Ensure the finalizer: if it is missing, add it and Update.
  4. Reconcile child resources: controllerutil.CreateOrUpdate (it does a Get first, then runs your mutate function, and only calls Create or Update if something differs), plus SetControllerReference.
  5. Reconcile external resources: in this example, a registration ConfigMap is written to the shop-registry namespace. It is cross-namespace, so ownerReference cannot be used, and a finalizer is required.
  6. Write status: readyReplicas, selector, URL, conditions, and observedGeneration, using r.Status().Update.
  7. Return: an error means backoff and retry. If you need a timed check, return ctrl.Result{RequeueAfter: …}. Otherwise, return ctrl.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).
Common misconceptions ① "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

shopapp_types.go// +kubebuilder:validation:…// +kubebuilder:subresource:status// +kubebuilder:printcolumn:…shopapp_controller.go: rbac controller-genmake manifestsmake generate(DeepCopy) config/crd/bases/shop.example.com_shopapps.yamlrbac/role.yaml (ClusterRole)manager/manager.yamldefault/ (Kustomize) Clustermake install → CRDmake deploy → ns shop-operator-systemSA + ClusterRole(Binding)Deployment controller-manager Manager process (cmd/main.go) Shared cacheShopApp / Deploy / Svc Controller "shopapp"For + Owns → workqueue ShopAppReconcilerYour Reconcile() Leader electionLease <hash>.example.com Probes / metrics:8081 healthz · :8443
Figure 4-1: markers are the single source of truth. controller-gen generates the CRD and RBAC. The Manager combines the cache, the controllers, and leader election in one process.

Objects managed by the ShopApp Operator

ShopApp shop/demofinalizer: shop.example.com/registrystatus.conditions[Available] Deployment shop/demoownerRef controller=true Service shop/demoownerRef controller=true ConfigMap shop-registry/shop-demoCross-namespace: cannot use ownerReferenceDeletion handled by a finalizer (simulates a "resource outside the cluster")
Figure 4-2: child resources in the same namespace inside the cluster are handled by GC. Resources in other namespaces or outside the cluster are handled by a finalizer.

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

Go codetypes + marker controller-genCRD · RBAC make installCRD into cluster go run ./cmd/main.goLocal process Manager startsCache sync · controller · Lease kubectl applyShopApp demo Reconcile: finalizer → Deployment/Service → registration → statusLog: Reconciling … operation=created
Ready. Click Play.
$ make manifests generate

Command table

CommandPurposeNotes
kubebuilder init --domain example.com --repo example.com/shop-operatorInitialize the project (go.mod, Makefile, cmd/main.go, config/)Full group name = <group>.<domain>
kubebuilder create api --group shop --version v1alpha1 --kind ShopAppGenerate the type and controllerAdd --resource --controller to skip the interactive prompts
kubebuilder create webhook --group shop --version v1alpha1 --kind ShopApp --defaulting --programmatic-validationGenerate an admission webhook (requires cert-manager)For multiple versions, use --conversion (check the book for the exact options)
make manifests / make generateGenerate CRD, RBAC / DeepCopyMust be run after changing types or markers
make install / make uninstallInstall / delete CRDuninstall deletes all CRs
make runRun the controller locally in the foregroundUses the current kubeconfig
make testenvtest testsThe first run downloads the etcd / kube-apiserver test binaries
make docker-build IMG=… / make deploy IMG=… / make undeployBuild image / deploy / uninstallkind: insert kind load docker-image in the middle
make build-installer IMG=…Generate a single file dist/install.yamlEasier 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.

A detail about CreateOrUpdate The mutate function replaces the whole containers list. The apiserver then fills in default values (imagePullPolicy, terminationMessagePath, and so on), so every comparison finds a "difference" and sends one Update. On the apiserver side, that Update is a no-op write: it creates no new resourceVersion and no event, so it does not form a loop, but it adds one extra API call. At scale, switch to server-side apply or set only the fields you care about.

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)

Goal: generate the project, implement Reconcile, run it locally, deploy it to kind, and verify self-healing, scaling, the finalizer and RBAC. Environment: Go 1.26 from Module 0, kubebuilder 4.16.0, and the kind lab.
Generate the project and write the code: follow sections 1–3 on the Commands tab, then run 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
Run locally: follow section 4 with make install and make run. In another terminal, create the demo, and confirm the Deployment, the Service, the registry ConfigMap and the status conditions.
Self-healing and scaling
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
Deploy to the cluster: press Ctrl+C to stop 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
Finalizer flow
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
Deliberately cause missing RBAC: delete the RBAC marker for configmaps, run 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.
Verify: in the output of 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.
Cleanup: keep the Operator and the demo for the capstone lab. To clean up everything, run 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.

Command-line exercise

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)

▶
Kubernetes Operator Best Practices – Kubebuilder Deep Dive — freeCodeCamp.org
English · duration and upload date not verified · Use: kubebuilder project structure, markers and how to write Reconcile (the version in the video may predate v4.16, so follow the commands on this page)
▶
Kubernetes Operator simply explained in 10 mins — TechWorld with Nana
English · duration and upload date not verified · Use: a review of why Operators exist

Official documentation

Video storyboard script

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: the terminal runs kubebuilder init and create api. The directory tree expands level by level, with api, internal/controller and config highlighted.
Narration: two commands give you a complete project. You only need to change the types and Reconcile.
Shot 2 · 0:25–0:55
Visual: the marker comments on the Go struct fly to the right and turn into minimum, default and x-kubernetes-validations in the CRD YAML.
Narration: markers are the single source of truth. make manifests turns them into the CRD and RBAC.
Shot 3 · 0:55–1:30
Visual: the Reconcile function is highlighted in seven parts, in order: read, the delete branch, add the finalizer, Deployment, Service, registration and status.
Narration: each part is idempotent. Run it again, and the result does not change.
Shot 4 · 1:30–1:55
Visual: make run and make deploy are compared side by side. The right side adds a ServiceAccount, a ClusterRole and a Lease.
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.
or score 70% or higher on the quiz

Module 5 · Using Existing Operators: OLM, Maturity and Selection

28:00 – 35:00 · Most teams use far more Operators than they write: databases, certificates, message queues and monitoring. Review them before you install, and make sure you can upgrade and uninstall them afterward
7 minOLM v1 operator-controller v1.12.0 · CloudNativePG 1.30.2★★★★☆ One Operator = one long-lived dependency with cluster-level permissions
Learning goals
  • 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.
Prerequisites: hour 3 M1–M2 (Service, kube-proxy), M6 (Gateway API), M7 (NetworkPolicy); hour 4 M6 (StatefulSet + PostgreSQL); hour 5 M2 (RBAC). Importance: ★★★★☆

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:

LevelNameMeaningExample
1Basic InstallAutomated installation and configurationCreates a StatefulSet and Service from the CR
2Seamless UpgradesSupports patch and minor upgrades of the Operator itself and of the managed applicationChange the version number in the CR to roll out an upgrade
3Full LifecycleFull lifecycle: backup, restore, failover, scalingScheduled backups to object storage, PITR
4Deep InsightsMetrics, alerts, log handling, workload analysisExposes Prometheus metrics and alerting rules
5Auto PilotAutomatic scaling, auto-tuning, anomaly detection and self-healingAdjusts 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: Fail blocks 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

MethodMechanismProsCons
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 GitOpsYou handle upgrades and rollbacks yourself, and you judge version compatibility yourself
Helm ChartThe Chart from hour 6Parameterized, with the widest ecosystemHelm 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 releasesMany 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 GitOpsSupports 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).
Common misconceptions (1) "A level 5 Operator on OperatorHub is the most mature one." The levels are self-reported, and they describe only the scope of features, not quality. (2) "If an Operator manages my database, I don't need a DBA." An Operator automates known procedures. Capacity planning, slow queries and data repair still need expert skills. (3) "Uninstalling just means deleting the Operator's Deployment." You must first handle the CRs (back up, delete, or remove the finalizers), then delete the controller, and finally delete the CRDs. (4) "Two teams in the same cluster can each install their own version." CRDs are cluster-scoped, so there can be only one. Multi-tenant setups usually need separate clusters or a platform team that provides the Operator centrally.

OLM v0 and OLM v1 object relationships

OLM v0 (OpenShift and similar) CatalogSourceIndex image (catalog) OperatorGroupWhich namespaces it watches SubscriptionPackage + channel + approval mode InstallPlanAutomatic / Manual ClusterServiceVersionDeployment · RBAC · CRD ownership OLM v1 (operator-controller) ClusterCatalogCatalog image (unpacked by catalogd) ClusterExtensionPackage name · version range · channel Installed resourcesCRD · RBAC · DeploymentManaged by operator-controller
Figure 5-1 OLM v0 uses four or five kinds of objects to describe what to install, where to install it from, who it is installed for, and how to upgrade it. OLM v1 simplifies this to two cluster-scoped objects: a catalog and an extension.

CloudNativePG topology in shop

cnpg-systemcnpg-controller-managerwatch Cluster / Backup … Cluster shop/shop-dbinstances: 3status.currentPrimary shop-db-1primary · PVC shop-db-2replica · streaming replication shop-db-3replica · streaming replication Service shop-db-rwPoints only to the primary (read-write) Service shop-db-ro / -rRead-only replicas / any instance Secret shop-db-appApp user · uri · password CNPG does not use StatefulSets:It manages Pods and PVCs directly and decides for itselfUpgrade order, primary switchover and Service targets
Figure 5-2 The Operator encodes the DBA knowledge of replication, failover and Service switching into a controller. Users write only one Cluster object.

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.

Project and capabilities
Security and operations
Check the conditions, then click "Evaluate".
Waiting for evaluation…

"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

CommandPurposeNotes
kubectl apply --server-side -f https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/cnpg-1.30.2.yamlInstall CloudNativePG 1.30.2The CRDs are large, so you must use server-side apply
kubectl get crd -l <label> / kubectl get crd | grep cnpg.ioList the CRDs the Operator bringsAssess the number and versions of CRDs
kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa>Audit the Operator's effective permissionsFocus on secrets, pods/exec and webhook configuration
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations | grep cnpgList the webhooks the Operator registersfailurePolicy, namespaceSelector
kubectl get clustercatalogs,clusterextensionsOLM v1 objectsInstall operator-controller first
kubectl get subscriptions,csv,installplans -AOLM v0 objectsCommon 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)

Goal: complete one full cycle: review before install → install → use → failover → uninstall. Environment: kind lab. It needs about 1.5 GiB of memory for the 3 PostgreSQL instances.
Pre-install review: open CloudNativePG's GitHub Releases and documentation. Fill in the scorer on the animation tab, and record the supported Kubernetes versions, the dates of the last 3 releases, and whether the upgrade notes involve CRDs.
Install and audit: run section 1 on the Commands tab, and save the permission audit output to cnpg-audit.txt.
Create the database and connect: run section 2, then connect from inside the cluster:
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
Failover: run section 3 and record how long the switchover takes. Query the orders table again, and confirm the data is still there.
Experience "permissions are risk":
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).

Verify: kubectl -n shop get cluster shop-db shows healthy, and you can explain the difference between the rw, ro and r Services.
Uninstall in the correct order (do it now if memory is tight; otherwise do it after the capstone lab):
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.

Command-line exercise

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 secrets

2. 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)

▶
Kubernetes Operator simply explained in 10 mins — TechWorld with Nana
English · duration and upload date not verified · Use: understand the value of an Operator replacing manual operations, using a database as the example

No verified explainer videos for OLM v1 or CloudNativePG were found. Follow the official documentation and the storyboard instead.

Official documentation

Video storyboard script

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual: five steps: basic install, seamless upgrades, full lifecycle, deep insights, auto pilot. A database icon climbs the steps one by one.
Narration: capability levels describe how much operations work an Operator does for you, but the publisher reports them themselves.
Shot 2 · 0:25–0:55
Visual: the Operator's ClusterRole expands, and the secrets line turns red. Next to the webhook configuration, a warning appears: "all writes blocked".
Narration: installing an Operator means granting cluster-level permissions to a long-running program. It must be reviewed.
Shot 3 · 0:55–1:25
Visual: three PostgreSQL Pods. The primary is deleted, a replica is promoted to primary, and the arrow to the rw Service turns to point to the new primary.
Narration: CloudNativePG encodes primary switchover in its controller. Applications only ever need to connect to the rw Service.
Shot 4 · 1:25–1:50
Visual: the three uninstall steps: delete the CR, delete the Operator, delete the CRD. If you do them in reverse, the namespace gets stuck in Terminating.
Narration: the uninstall order matters just as much as the install order.
or score 70% or higher on the quiz

Module 6 · Service Mesh Fundamentals: Sidecars, Ambient and mTLS

35:00 – 42:00 · A mesh moves service-to-service encryption, identity, authorization, retries, traffic splitting and telemetry out of application code and into the infrastructure layer. The cost is an extra proxy layer and a control plane.
7 minIstio 1.32 · ambient (GA since 1.24) · HBONE 15008 · SPIFFE★★★★☆ Decide first whether you need it
Learning goals
  • 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.
Prerequisites: hour 3 M1–M2 (Service, kube-proxy), M6 (Gateway API), M7 (NetworkPolicy); hour 5 M3 (ServiceAccount). Importance: ★★★★☆

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-proxy container). 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)

RequirementWithout a meshWith a mesh
Service-to-service encryption and mutual authenticationEach 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 portAuthorizationPolicy matches by SPIFFE identity + HTTP method / path
90/10 canary, header-based routing, timeouts, retries, circuit breakingWritten in the app or SDK, and inconsistent across languagesConfigured uniformly with HTTPRoute / VirtualService
Service topology and golden signalsEach application instruments itselfProxies 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

DimensionSidecar modeAmbient mode
How workloads join the meshNamespace label istio-injection=enabled. Restart the Pods to inject istio-proxy.Namespace label istio.io/dataplane-mode=ambient. No Pod restart needed.
Traffic interceptioniptables in the Pod's network namespace (istio-init or istio-cni) redirects traffic to Envoy on 15001 / 15006The istio-cni node agent configures redirection in the Pod's network namespace, and traffic is handed to the ztunnel on the same node
mTLS transportTLS between Envoy and EnvoyHBONE between ztunnel and ztunnel (an mTLS tunnel based on HTTP/2 CONNECT, on port 15008)
L7 capabilitiesEvery sidecar has themOnly traffic that passes through a waypoint has them (deployed on demand, istio.io/use-waypoint)
Resource usageOne Envoy per Pod (CPU and memory grow linearly with the number of Pods)One ztunnel per node plus a few waypoints, usually much lower
UpgradesUpgrading the data plane = restarting all application PodsUpgrading ztunnel / waypoints is decoupled from application Pods
OtherThe 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.

Common misconceptions (1) "With a mesh, you don't need NetworkPolicy." They complement each other. The mesh handles L7 identity-based authorization, and NetworkPolicy is a backstop at the kernel / CNI layer (for example, it blocks traffic that bypasses the mesh). (2) "Ambient has no Envoy." The L4 ztunnel is not Envoy, but the L7 waypoint is Envoy. (3) "Turning on mTLS means changing application code." It does not. Applications still send plain HTTP, and the proxy handles encryption. (4) "In ambient, an HTTPRoute takes effect immediately." L7 rules need a waypoint. Without a waypoint, ztunnel can enforce only L4 policies.

Sidecar and ambient architecture comparison

Sidecar mode Pod webnginxistio-proxyEnvoy Pod apiistio-proxyEnvoypodinfo mTLS istiod: xDS configuration + CAEach Envoy has full L7 configuration +1 container per Pod · injection requires a restart · L4 and L7 both live in the sidecar Ambient mode Node Aweb (no sidecar)ztunnel (DaemonSet, L4) Node Bapiztunnel (L4) HBONE waypoint (optional, Envoy, L7)Deployed per namespace / service Joining only needs a label · no restart · pay for L7 only when you need it
Figure 6-1 Sidecar puts a proxy in every Pod. Ambient moves L4 down to the node-level ztunnel and hands L7 to the optional waypoint.

Certificates and identity: from ServiceAccount to mTLS

The Pod's ServiceAccountshop/apiProjected token (JWT) ztunnel / istio-proxyGenerate private key + CSRAttach the token to prove identity istiod (CA)TokenReview checkIssue short-lived certificate X.509 SAN: spiffe://cluster.local/ns/shop/sa/apiThe default validity is short (about 24 hours), and it rotates automatically before it expiresThe private key is not written to disk or stored in a Secret The principals in an AuthorizationPolicy use this identity (without the spiffe:// prefix): cluster.local/ns/shop/sa/web
Figure 6-2 Mesh identity = ServiceAccount. So a dedicated ServiceAccount for each service is a prerequisite for using mesh authorization.

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.

web containerGET http://api:9898 Source ztunnelNode A waypointHTTPRoute · L7 authorization Destination ztunnelNode B api containerpodinfo :9898 istiodxDS · certificate issuance
Ready. Click "Play".
$ kubectl -n shop exec deploy/web -- wget -qO- http://api:9898/version

Command table (this module focuses on concepts; use these commands to see the data plane clearly)

CommandPurposeNotes
kubectl label ns shop istio.io/dataplane-mode=ambientAdd a namespace to ambientNo Pod restart needed
kubectl label ns shop istio-injection=enabledEnable sidecar injection for a namespaceRequires kubectl rollout restart
istioctl ztunnel-config workloadsWorkloads as seen by ztunnel (protocol HBONE / TCP, waypoint)Confirm whether the workload has joined the mesh
istioctl ztunnel-config certificates <ztunnel-pod>.istio-systemCertificates held by ztunnel (leaf / root, validity period)Troubleshoot certificate problems
istioctl proxy-config secret deploy/<name> -n shopCertificates held by the sidecarSidecar 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)

Goal: based on shop's current state, write a decision record (ADR) on whether to introduce a mesh and which data plane to choose. You install it hands-on in M7.
Collect the current state
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
Estimate the overhead: assume a production cluster with 30 nodes and 900 Pods. Estimate 50–100 MiB of memory per sidecar, tens of MiB per node for ztunnel, and one waypoint per namespace (tens to over a hundred MiB). Calculate the order of magnitude of total memory for both options. These numbers are classroom estimates, so use measurements from your own environment.
Fill in the decision table:
QuestionYour 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…
Verify: your ADR states why you did not choose the other option, and it includes a rollback plan (for ambient: removing the namespace label is enough to leave the mesh).
Cleanup: none (read-only).

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'
Command-line exercises

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)

▶
Istio & Service Mesh - simply explained in 15 mins — TechWorld with Nana
English · Duration and upload date not verified · Recorded before ambient mode; use it only to understand the motivation for a mesh and the sidecar architecture
▶
Istio Service Mesh Explained — IBM Technology
English · Duration and upload date not verified · Use: control plane / data plane and mTLS concepts
▶
What is a service mesh — HashiCorp, an IBM Company
English · Duration and upload date not verified · Use: mesh concepts that are not tied to a specific product

Official docs

Video storyboard

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
On screen: Lines connecting ten services, each labeled “Encryption? Retries? Authorization? Metrics?”
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.
Shot 2 · 0:25–0:55
On screen: Each Pod on the left gets an extra proxy. On the right, each node runs one ztunnel, and a waypoint lights up beside them when needed.
Narration: Sidecar mode runs one proxy per Pod. Ambient moves L4 down to the node and adds L7 only when needed.
Shot 3 · 0:55–1:25
On screen: The ServiceAccount becomes a certificate with a SPIFFE address printed on it. The two ztunnels present their certificates to each other and set up an HBONE tunnel.
Narration: The mesh identity comes from the ServiceAccount, and authorization is based on identity, not IP.
Shot 4 · 1:25–1:50
On screen: A decision checklist: few services, only ingress needed, only encryption needed. All three branches say “No mesh needed.”
Narration: A mesh is a platform capability, not the default choice.
Or score ≥ 70% on the quiz

Module 7 · Istio in Practice: Traffic Splitting, mTLS and Observability

42:00 – 50:00 · Install Istio 1.32 ambient on kind and bring shop into the mesh: automatic mTLS → STRICT → identity-based authorization → waypoint → HTTPRoute 90/10 canary → Kiali topology
8 minIstio 1.32.0 · profile=ambient · Gateway API v1.6 · security.istio.io/v1★★★★☆ Hands-on module
Learning goals
  • 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.
Prerequisites: M6; hour 3 M6 (HTTPRoute syntax). Importance: ★★★★☆

What: Istio APIs used in this module

ObjectAPIPurposeWho executes it in ambient
PeerAuthenticationsecurity.istio.io/v1Inbound mTLS mode: PERMISSIVE (default, accepts both plaintext and mTLS) / STRICT (accepts only mTLS)ztunnel
AuthorizationPolicy (selector)security.istio.io/v1L4 authorization: source identity (principals), source namespace, IP, portDestination ztunnel
AuthorizationPolicy (targetRefs)security.istio.io/v1L7 authorization: adds HTTP method, path, and headerswaypoint
Gateway (gatewayClassName: istio-waypoint)gateway.networking.k8s.io/v1Declares a waypoint proxy (generated by istioctl waypoint apply)istiod creates a Deployment for it
HTTPRoute (parentRefs: kind: Service)gateway.networking.k8s.io/v1East-west L7 routing: weights, header matching, timeouts, retrieswaypoint

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

  1. 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).
  2. Join namespaces one at a time (PERMISSIVE), and watch the ztunnel logs and Kiali for 1–2 weeks to find callers outside the mesh.
  3. Configure a dedicated ServiceAccount for each service, then write authorization policies (AUDIT / observe first, then ALLOW).
  4. Switch to STRICT, and deploy waypoints only for services that need L7.
  5. 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).
Common misconceptions ① “Installing Istio turns on STRICT by default.” No, the default is PERMISSIVE. ② “Writing rules other than DENY makes it more secure.” An ALLOW policy denies all other sources, so first confirm every legitimate caller (including Prometheus scrapes, health checks, and the waypoint). ③ “Attaching an HTTPRoute to a Service takes effect automatically.” In ambient, there must be a waypoint, and the Service must be bound to it. ④ “Kiali is a required Istio component.” The Prometheus / Kiali in samples/addons are for demos only; in production, install them according to each project's own method.

Topology of shop after this module

Namespace shop (istio.io/dataplane-mode=ambient · istio.io/use-waypoint=waypoint · STRICT) webSA: web waypoint (SA: waypoint)HTTPRoute api 90/10L7 policy: only GET from web api-v1 (app=api)Service api-v1 · 90% api-v2 (app=api-v2)Service api-v2 · 10% HBONE L4 policy (ztunnel, selector app=api / app=api-v2): allow only the waypoint identitycluster.local/ns/shop/sa/waypoint —— traffic that bypasses the waypoint and connects directly to Pod IPs is also denied Namespace legacyNot in the mesh (plaintext) STRICT: connection reset istio-systemistiod · ztunnel · cni
Figure 7-1 Security is enforced at two layers: ztunnel ensures “only the waypoint can get in,” and the waypoint ensures “only GET requests from web get through” and handles the 90/10 split

Steps for a canary rollout

100 / 0Deploy v2 with no traffic 90 / 10Watch error rate / latency 50 / 50Compare metrics between the two versions 0 / 100Full cutover to v2 Roll backAt any stage, set the weights back to 100 / 0 At each step, you only change the weight in HTTPRoute. With Argo Rollouts / Flagger, you can advance automatically based on Prometheus metrics (hour 6 GitOps).
Figure 7-2 Changing weights for a canary is a “change one field” operation, which suits GitOps and progressive delivery tools

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.

HTTPRoute weights

api-v2 weight: 10%

Security policies

Clients: Method:

Adjust the parameters, then click the button.
$ kubectl -n shop exec deploy/web -- wget -qO- http://api:9898/

Command table

CommandPurposeNotes
istioctl install --set profile=ambient --skip-confirmationInstall ambient (istiod + istio-cni + ztunnel)For sidecar, use profile=default
istioctl waypoint apply -n shop --enroll-namespace --waitDeploy a waypoint and label the namespace with istio.io/use-waypointistioctl waypoint list -n shop
istioctl analyze -n shopStatically check for configuration problemsAlso works in CI
istioctl ztunnel-config workloadsView mesh enrollment status and waypoint bindingsWAYPOINT column
istioctl dashboard kiali / prometheusOpen the dashboard with port forwardingFor a remote VM, add --address 0.0.0.0 or use an SSH tunnel
istioctl uninstall --purge -yUninstall IstioDelete 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)

Goal: Complete, in order, installation → enrollment → STRICT → L4 authorization → waypoint + L7 authorization → canary → observation → cleanup, and verify each step with both a positive and a negative test. Environment: kind lab, with at least 2 GiB of free memory.
Installation and setup: Run sections 1–2 of the Commands list. Verify: kubectl -n shop get pods -o custom-columns=N:.metadata.name,SA:.spec.serviceAccountName shows the dedicated SAs for web / api.
Enrollment and STRICT: Run section 3, then prepare two test clients, one inside the mesh and one outside it:
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
Waypoint, L7 authorization, and canary: Run section 4. Then verify how an L7 denial appears:
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.

Advance and roll back: Change the weights to 50/50 and tally the results. Then change them back to 100/0 to simulate a rollback:
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}]'
Observation: Run section 5, open the Traffic Graph in Kiali (namespace shop), and confirm the topology of web → waypoint → api-v1 / api-v2 and the lock icons (mTLS). Then run the sample query in Prometheus.
Verification: Complete these 4 checks: ① web GET succeeds; ② shop/curl and legacy/curl are reset; ③ web POST returns 403; ④ out of 100 requests, about 10% reach v2.
Cleanup (you can postpone this if the capstone lab still needs Istio):
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 shop
istioctl 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
Command-line exercises

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)

▶
Istio & Service Mesh - simply explained in 15 mins — TechWorld with Nana
English · Duration and upload date not verified · Predates ambient, but the traffic splitting and mTLS concepts still apply; follow this page for commands
▶
Istio Service Mesh Explained — IBM Technology
English · Duration and upload date not verified · Use: security and traffic management concepts

No verified hands-on video based on Istio 1.3x ambient was found.

Official docs

Video storyboard

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:20
On screen: In a terminal, run istioctl install; three components appear in turn: istiod, istio-cni, and ztunnel.
Narration: An ambient install has only three parts: the control plane, a CNI node agent, and one ztunnel per node.
Shot 2 · 0:20–0:50
On screen: The shop namespace gets labeled, and lock icons appear instantly on the lines between Pods; after STRICT is enabled, requests from the legacy namespace bounce back.
Narration: Joining the mesh gives you mTLS immediately, and STRICT closes the plaintext back door.
Shot 3 · 0:50–1:25
On screen: A waypoint appears between web and api, 100 requests are split 9 to 1, and POST requests are stopped with a 403.
Narration: All the L7 capabilities live in the waypoint: canary releases, method-based authorization, and RBAC access denied responses when requests are rejected.
Shot 4 · 1:25–1:50
On screen: The Kiali topology: web to the waypoint, then to both versions, with request rate and success rate shown on the edges.
Narration: Use metrics to decide whether to continue the canary, and you can always set the weights back.
Or score ≥ 70% on the quiz

Module 8 · Extending Reviews, Troubleshooting and Self-Check

50:00 – 60:00 · Every extension adds a “component that can fail” to the cluster. Know what breaks when it goes down, how to detect it, how to recover, and how to uninstall it safely
10 minwebhook · conversion · finalizer · istiod / ztunnel★★★★★ Blast-radius management
Learning goals
  • 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.
Prerequisites: M1–M7. Importance: ★★★★★

What: Failure modes of extension components

Component downWhat breaksWhat keeps workingMitigation
Operator controllerNew or changed CRs have no effect; deleting a CR with a finalizer gets stuck; status stops updatingChild 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 PodsUse VAP / CRD CEL where possible instead of a webhook; exclude system namespaces with namespaceSelector; multiple replicas + PDB; a small timeoutSeconds
conversion webhookReads, writes, list, and watch fail for non-storage versions; controllers and GitOps tools using old versions go blindClients accessing the storage versionControllers use the storage version; webhooks are highly available; certificates rotate automatically
Aggregated API backendRequests for that group; discovery warnings, which can slow namespace deletion and some toolsOther APIsDelete the APIService when it is not in use; monitor its Available condition
istiodNew configuration is not delivered; new workloads cannot get certificates; certificates cannot be renewed after they expireExisting 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 nodeMesh traffic for enrolled Pods on that nodeOther nodesDaemonSet rolling-update strategy; node-level alerts
waypointAll L7 traffic passing through this waypointTraffic that uses only L4Waypoint 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

  1. Back up the CRs: kubectl get <crd> -A -o yaml > backup.yaml (Velero can also back up CRs; see hour 4 M7).
  2. Delete the CRs and wait for the controller to run finalizer cleanup (a database Operator may delete PVCs, so confirm the retention policy first).
  3. 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.
  4. Delete the CRD (this deletes all remaining CRs).
  5. 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.
Common misconceptions ① “Use 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

Large: affects writes for all teamsfailurePolicy: Fail webhook (matches Pods)Conversion webhook (clients on older versions)Unavailable aggregated API (discovery)istiod down for a long time (certificates expire)→ Requires an SLO, alerts, and an emergency kill switch Medium: affects one resource type or some nodesOperator controller (CRs have no effect, deletion gets stuck)A single node's ztunnel / istio-cniWaypoint (L7 traffic in its scope)Leftover finalizers (namespace cannot be deleted)→ Multiple replicas, PDB, a clear uninstall order Small: affects only itselfCEL rules inside a CRD (run inside the apiserver)VAP / MAP (run inside the apiserver)Printer columns, selectableFieldsRead-only controllers without a webhook→ Prefer options in this column first
Figure 8-1 When designing an extension, prefer mechanisms that run “inside the apiserver process.” Any extension point that makes network calls should be treated as critical infrastructure.

Uninstall order

① Back up CRsget -o yaml / Velero ② Delete CRsWait for finalizers to complete ③ Delete webhook configurationsAvoids blocking writes ④ Delete controller + RBACmake undeploy ⑤ Delete CRDmake uninstall
Figure 8-2 If the order is reversed (deleting the controller or CRD first), you get stuck Terminating resources or blocked writes

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.

Choose a failure scenario.
Waiting for a selection…

Command table

CommandPurpose
kubectl get <plural>.<group> -A -o yaml > backup.yamlBack 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 FalseFind unavailable aggregated APIs
istioctl analyze -A, istioctl proxy-statusMesh configuration checks, proxy sync status
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestampCluster-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)

Goal: Cause three extension failures yourself and recover from each one using the troubleshooting tree. Environment: the ShopApp Operator deployed in M4 (in-cluster), and Istio from M7 (if you already cleaned it up, you can skip step 4).
Fault 1: Controller down + finalizer
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: NotFound
Fault 2: Fail-policy webhook pointing to a Service that does not exist
kubectl 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.

Fault 3: Wrong uninstall order
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.

Fault 4 (optional): Mesh: Delete the waypoint, then observe the effect on the HTTPRoute weights and the L4 policy. Then run istioctl waypoint apply again.
Verification: Running ext-health.sh produces clean output, and you can explain each fault's “blast radius + first diagnostic command” out loud.
Cleanup: Set the controller replicas back to 1. To redo M4, run 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).

Command-line exercises

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

Video storyboard

This lesson cannot generate a video or MP3 directly, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
On screen: Three concentric circles: the inner circle is CEL and VAP, the middle circle is controllers and the waypoint, and the outer circle is webhooks and conversion.
Narration: The more an extension depends on network calls, the bigger the impact when it fails.
Shot 2 · 0:25–0:55
On screen: A webhook Pod goes down, and the deploy button turns gray across the whole cluster.
Narration: When a Fail-policy webhook goes down, it blocks every matching write, and it may even be unable to restart itself.
Shot 3 · 0:55–1:25
On screen: Five uninstall steps light up in order; then play it in reverse: delete the controller first, the CR gets stuck in Terminating, and the namespace gets stuck too.
Narration: The uninstall order is: back up, delete CRs, delete webhooks, delete the controller, delete the CRD.
Or score ≥ 70% on the quiz

Command cheat sheet

CRD · controllers · kubebuilder · Operator operations · Istio ambient
Inventory extension points
kubectl api-resources --api-group=<group> -o wide
kubectl get crd
kubectl get apiservices | grep -v Local
kubectl get validatingadmissionpolicies
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
CRD
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=backend
Subresources and controller watches
kubectl 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 -A
kubebuilder
kubebuilder 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
Off-the-shelf Operators
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
Istio ambient
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
Finalizer emergency removal (only after confirming external resources are cleaned up)
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}'
Uninstall order
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

SymptomMost likely causeFirst command
the server doesn't have a resource typeCRD not installed / not Establishedkubectl get crd | grep <name>
Invalid value: "string": <CEL message>Rejected by CRD CEL rulekubectl explain + read the message
strict decoding error: unknown fieldMisspelled field / version mismatchkubectl explain <kind>.spec
CR has no status and no subresourceController not running / insufficient RBACkubectl logs deploy/<controller>
CR / namespace stuck in TerminatingFinalizer with no one handling itkubectl get … -o jsonpath='{.metadata.finalizers}'
failed calling webhookWebhook backend unavailablekubectl get endpointslices -n <ns>
Connection reset by peer (after enrollment)STRICT or L4 policy denialkubectl -n istio-system logs -l app=ztunnel
HTTP 403 RBAC: access deniedL7 AuthorizationPolicykubectl get authorizationpolicy -n <ns>
HTTPRoute weights have no effectNo waypointistioctl waypoint list -n <ns>

Recommended config snippet

CRD: immutable fields + cross-field rules
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"
Webhook: limit the blast radius
failurePolicy: Fail
timeoutSeconds: 3
namespaceSelector:
  matchExpressions:
  - key: kubernetes.io/metadata.name
    operator: NotIn
    values: [kube-system, shop-operator-system]

Capstone lab + final quiz

Build a “platform” extension stack for shop: custom API → Operator → an off-the-shelf database Operator → mesh security and canary releases → safe uninstall
About 90 minkind lab · no cloud costs
Scenario

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.

Environment check: kubectl get nodes (v1.37), kubebuilder version, istioctl version --remote=false; kubectl -n shop get deploy web api.
ShopApp Operator: Complete M4 and run 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.

Validation regression: Use 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.
Database: Following M5, install CloudNativePG 1.30.2, create shop-db (3 instances), and delete the primary instance to drill failover.
Mesh: Following M7, install ambient, enroll shop, and enable STRICT. Deploy v2 of catalog (catalog-v2) and use HTTPRoute for a 90/10 split; the L7 policy allows only storefront's SA to call catalog's GET.
Fault drill: Following the M8 lab, cause two faults separately: “controller down + delete CR” and “Fail webhook.” Recover each using the troubleshooting tree, and record the recovery time.
Safe uninstall: Back up all ShopApps and Clusters → delete the CRs → make undeploy → make uninstall → uninstall CNPG → uninstall the mesh following the M7 cleanup steps → ext-health.sh produces clean output.
Acceptance checklist

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

Basis for verifying this lesson's technical facts (Verified on: 2026-11-18)
TopicVerification resultSource (verified on)
Kubernetes versionv1.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.37Course specification (verified 2026-11-15), hour 5 M6
CRD feature statusCEL 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 budgetCRD task page (2026-11-18)
kubebuilderv4.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 / uninstallGitHub Releases · Quick Start (2026-11-18)
Istio1.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 supportedSupported releases · Releases (2026-11-18)
Istio ambient commandsistioctl 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 / certificatesGetting started and its subpages, Troubleshoot ztunnel (2026-11-18)
Gateway APIv1.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 v1operator-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 deprecatedReleases · Install an extension (2026-11-18)
CloudNativePGv1.30.2 (2026-11-17), install manifest releases/download/v1.30.2/cnpg-1.30.2.yamlReleases (2026-11-18)
Lab environmentkind v0.33.0, node v1.37.0, the shop application, and Gateway API v1.6.3, consistent with the other hours in this courseCourse 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 init actually 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.