Lesson 91 · Section 7: Security
Lesson 91: Custom controllers: the loop that makes a custom resource real
What a controller is, the observe, compare and act loop behind every Kubernetes feature, how watches, caches and work queues make it efficient, what a custom controller for a custom resource looks like, and how to install, permit and troubleshoot one in a cluster. · 17 min read · 3 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why custom controllers exist
The previous lesson ended with a custom resource that did nothing. You defined a Backup kind with a CRD, created
an object called nightly with a schedule and a target, and Kubernetes stored it, validated it, and stopped there.
No Job ran and no backup was taken. A custom resource is data: a record of what someone wants.
Something has to read that record and make it true. In Kubernetes that something is always a controller: a
program that watches objects of a kind and changes the world until it matches what the objects ask for. Built-in
kinds have built-in controllers inside kube-controller-manager. A custom kind needs a custom controller,
written by whoever invented the kind and installed into the cluster like any other application.
How it works
The control loop
Parts:
- Desired state (the object's spec)
- Observe (read spec and world)
- Compare (what is missing?)
- Act (create, update, delete)
- Report (write status)
- Actual state (objects, cloud, apps)
Connections:
- Desired state to Observe: read
- Observe to Compare
- Compare to Act: gap
- Act to Report
- Act to Actual state: change
- Report to Observe: again
The name comes from control engineering: a thermostat reads the wanted temperature, measures the room, and switches the heating on or off. A Kubernetes controller does the same with objects:
- Observe. Read the object's
spec, and look at what exists: other objects, a cloud resource, a database. - Compare. Work out the difference. "This Backup wants a CronJob at 02:00, and there is none."
- Act. Take a step towards the desired state: create the CronJob, change its schedule, delete a leftover.
- Report. Write what it found into the object's
status, so users can see progress withkubectl get.
Then the loop runs again, for ever. You already know many controllers that work this way:
| Controller | Watches | Makes sure that |
|---|---|---|
| Deployment controller | Deployments | A ReplicaSet with the current template exists, and old ones scale down |
| ReplicaSet controller | ReplicaSets, Pods | The number of matching Pods equals replicas |
| Node controller | Nodes | Nodes that stop reporting are marked NotReady, and their Pods evicted |
| Endpoints / EndpointSlice controller | Services, Pods | Every Service lists the addresses of its ready Pods |
| Scheduler | Pods without a node | Every Pod gets a node |
| kubelet | Pods bound to its node | The containers of those Pods are running |
Level-triggered: why controllers heal themselves
A controller does not act on "what changed". It acts on "what is the state now". If the controller was down while three edits were made, it does not replay three events; it reads the latest spec and does whatever that needs. If someone deletes the CronJob by hand, the next round finds it missing and creates it again. This is why Kubernetes repairs itself after failures, and why a controller must be written so that running it twice in a row is harmless (it is idempotent).
It is also why you cannot "fight" a controller. Change a Pod's label so its ReplicaSet no longer matches it, and the ReplicaSet makes a new Pod. Scale down a Deployment's ReplicaSet directly, and the Deployment controller scales it back up. To change the result, change the object the controller watches.
Inside a controller
Parts:
- API server (list once, then watch)
- Informer (events: add, update)
- Local cache (reads cost nothing)
- Work queue (prod/nightly)
- Reconcile (one key at a time)
- Writes (objects and status)
Connections:
- API server to Informer: watch
- Informer to Local cache: store
- Informer to Work queue: key
- Work queue to Reconcile: pop
- Reconcile to Local cache: read
- Reconcile to Writes
- Writes to API server: send
Asking the API server for every object every second would overload it, so controllers are built from a few standard
parts, which come from the Go library client-go:
- Informer. Lists all objects of a kind once, then keeps a watch open. The API server streams every add, update and delete as an event.
- Cache. The informer keeps a local copy of every object it watches. The controller reads from it, so reads cost the API server nothing.
- Work queue. On every event the informer puts the object's key,
namespace/name, into a queue. Ten updates to the same object in one second become one entry. Failed keys are put back with a growing delay. - Reconcile. A worker takes one key from the queue and runs the loop for that object only. It is called "reconcile" because it reconciles the actual state with the desired state.
A controller usually also watches the objects it creates. When the CronJob made for nightly changes or is
deleted, the informer for CronJobs finds the owner and queues prod/nightly again.
Ownership and clean-up
When the controller creates the CronJob, it adds an owner reference pointing at the Backup:
metadata:
name: nightly-backup
ownerReferences:
- apiVersion: training.example.com/v1
kind: Backup
name: nightly
uid: 4f6c2a1e-9b0d-4c55-8a1f-2f0e7d3c9a11
controller: true
blockOwnerDeletion: true
Two things follow. Users can see which object a CronJob belongs to. And when the Backup is deleted, the garbage
collector in kube-controller-manager deletes the CronJob too, so the controller needs no clean-up code for
objects inside the cluster. This is exactly how deleting a Deployment removes its ReplicaSets and Pods.
For things outside the cluster, such as a bucket in a cloud account, the controller adds a finalizer to the
custom resource, for example training.example.com/cleanup. A kubectl delete then only sets a deletion
timestamp. The controller sees it, removes the external thing, and removes its finalizer; only then does the object
disappear.
Under the hood · Writing one: tools, leader election and status
- Languages and tools. Most controllers are written in Go with
controller-runtime, usually scaffolded with Kubebuilder or the Operator SDK (next lesson). Both generate the CRD from Go types, the RBAC rules from comments, and amain.gothat wires informers, queues and workers for you, so you only writeReconcile. Python (kopf), Java and other languages have similar frameworks; anything that can watch the API can be a controller, even a shell loop aroundkubectl get --watch. - Leader election. A controller Deployment often runs two or more replicas for availability, but only one may
act, or both would create the same CronJob. The replicas compete for a Lease object in their namespace; the
holder is the leader and the others wait.
kubectl -n backup-system get leaseshows who holds it. The built-inkube-controller-managerandkube-scheduleruse the same mechanism inkube-system. - The status subresource. With
subresources.statusin the CRD,specandstatusare written through different endpoints. Users writespec; the controller writesstatuswithr.Status().Update(...). RBAC can then give the controllerbackups/statuswithout letting it change what users asked for. observedGeneration. Every change tospecincreasesmetadata.generation. A controller copies the generation it last acted on intostatus.observedGeneration, so a mismatch means "not reconciled yet".- Conditions. Status usually holds a list of conditions such as
Ready=Truewith a reason and a message, the same shape as Pod and Node conditions.kubectl wait --for=condition=Ready backup/nightlyworks on them.
Using it
The CKA does not ask you to write a controller. It does expect you to install extensions built on CRDs and
controllers, and to tell why a custom resource has no effect. These examples use the Backup kind from the previous
lesson and a controller that turns each Backup into a CronJob.
Example · Install a controller and use it
Controllers usually ship as one manifest, or a Helm chart, that holds the CRDs, a namespace, the RBAC objects and the Deployment:
kubectl apply -f backup-controller.yaml
namespace/backup-system created
customresourcedefinition.apiextensions.k8s.io/backups.training.example.com created
serviceaccount/backup-controller created
clusterrole.rbac.authorization.k8s.io/backup-controller created
clusterrolebinding.rbac.authorization.k8s.io/backup-controller created
deployment.apps/backup-controller created
Parts:
- CRD (kind: Backup)
- Deployment (backup-controller)
- ServiceAccount (its identity)
- ClusterRole (backups, cronjobs)
- Backup nightly (you create it)
- CronJob (owned by nightly)
Connections:
- Deployment to ServiceAccount: runs as
- ServiceAccount to ClusterRole: bound to
- Deployment to Backup nightly: watches
- Backup nightly to CronJob: becomes
- CRD to Backup nightly: defines
Wait for the controller to run, then create a Backup and look for what the controller made:
kubectl -n backup-system rollout status deploy/backup-controller
kubectl -n prod apply -f nightly.yaml
kubectl -n prod get backup,cronjob
deployment "backup-controller" successfully rolled out
backup.training.example.com/nightly created
NAME AGE
backup.training.example.com/nightly 5s
NAME SCHEDULE TIMEZONE SUSPEND ACTIVE LAST SCHEDULE AGE
cronjob.batch/nightly-backup 0 2 * * * <none> False 0 <none> 4s
Change the schedule in the Backup and the controller updates the CronJob. Delete the CronJob by hand and it comes back within a second. Delete the Backup and the CronJob goes with it, through the owner reference.
Example · Read the RBAC a controller needs
The ClusterRole in that manifest shows everything the controller is allowed to do:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: backup-controller
rules:
- apiGroups: ["training.example.com"]
resources: ["backups"]
verbs: ["get", "list", "watch"]
- apiGroups: ["training.example.com"]
resources: ["backups/status"]
verbs: ["get", "update", "patch"]
- apiGroups: ["batch"]
resources: ["cronjobs"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["coordination.k8s.io"]
resources: ["leases"]
verbs: ["get", "create", "update"]
list and watch are what informers need; without them the controller cannot even start its cache. The status
rule is a separate resource, backups/status. And the last rule is for leader election. A ClusterRoleBinding gives
all of this to the ServiceAccount backup-controller in backup-system.
Example · Find out why a custom resource has no effect
A Backup exists, but no CronJob appears. Work from the object towards the controller:
kubectl -n prod describe backup nightly # any status, conditions or events?
kubectl get deploy -A | grep -i backup # is a controller installed and running?
kubectl -n backup-system logs deploy/backup-controller --tail=20
ERROR Reconciler error {"controller": "backup", "namespace": "prod", "name": "nightly",
"error": "cronjobs.batch is forbidden: User \"system:serviceaccount:backup-system:backup-controller\"
cannot create resource \"cronjobs\" in API group \"batch\" in the namespace \"prod\""}
The log names the user, the verb, the resource and the group. Confirm it and fix the ClusterRole:
kubectl auth can-i create cronjobs.batch -n prod \
--as=system:serviceaccount:backup-system:backup-controller
kubectl edit clusterrole backup-controller # add "create" to the cronjobs rule
The work queue retries the failed key with a growing delay, so the CronJob appears shortly after the fix, with no
restart. The other usual causes: no controller installed at all (the Backup has an empty status for ever), the
controller Pod crashing (CrashLoopBackOff, read logs --previous), or a controller that only watches certain
namespaces (check its arguments in the Deployment).
Example · See which controller owns an object
kubectl -n prod get cronjob nightly-backup \
-o jsonpath='{.metadata.ownerReferences[*].kind}/{.metadata.ownerReferences[*].name}{"\n"}'
Backup/nightly
The same check on a Pod shows ReplicaSet/web-7c9f5d8b6, and on that ReplicaSet Deployment/web. Following owner
references tells you which object to edit: changing the owned object directly is undone by the next reconcile.
Tricks
Common mistakes
- Expecting a CRD to do something. Without a running controller, a custom resource is only stored data.
- Editing objects a controller owns. The next reconcile undoes the change. Edit the owner.
- Giving the controller
getbut notlistandwatch. Informers need both, and the controller stalls at start-up. - Forgetting
backups/status. The controller does its work but cannot report it, and logs a forbidden error. - Uninstalling the controller before its custom resources. Objects with finalizers can then never finish deleting. Delete the custom resources first, then the controller, then the CRDs.
- Looking for the controller in
kube-system. Custom controllers live in their own namespace; search with-A.
Recap
- A controller is a loop: observe the desired and actual state, compare, act, report in
status, repeat. - Controllers are level-triggered and idempotent, which is why Kubernetes heals itself and why you cannot fight one.
- Inside: an informer lists and watches, a cache serves reads, a work queue holds keys, and
Reconcilehandles one object at a time. - A custom controller does this for a custom resource, runs as a Deployment, and needs RBAC for every kind it
touches, including
list,watchand the status subresource. - Owner references let the garbage collector delete what a controller created; finalizers let it clean up outside the cluster.
- A CRD plus a controller that knows one application is an operator, the topic of the next lesson.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.