Writing Kubernetes Operators in Go
Authoring an operator with kubebuilder and controller-runtime: the Manager/Cache/Client architecture, idempotent level-triggered reconciliation, finalizers, status conditions, RBAC markers, and envtest.
Overview
Writing an operator that survives production
The concepts topic covers what a CRD is, what the Operator Framework capability levels mean and when an operator is the right answer. This topic assumes all of that and deals with the part that takes the time: writing one that survives production.
At its heart an operator is a loop. Each turn of it goes through the same six steps.
- Watch events arrive from the API server.
- Each event becomes a key, namespace/name, in a rate-limited workqueue.
- A worker takes the key and calls Reconcile(ctx, req).
- Reconcile gets the current state through the cached client.
- It compares the spec with what it observes. If there is a gap, it creates, patches or deletes children and then writes status. If the object has converged, it does nothing.
- If the status write fails with 409 Conflict, the key goes back on the queue and the loop runs again.
The rest of this chapter explains why the loop is shaped this way. Three ideas carry most of the weight, but first the tools.
Key concepts
- Manager
- Cache and split Client
- Level-triggered reconciliation
- ctrl.Result and requeue
- ownerReference
- Status subresource and conditions
- Finalizer
- envtest
Interview questions
- Why does Reconcile take only a NamespacedName, and what does level-triggered actually mean for the code you write?
- Walk me through kubebuilder scaffolding. What does each generated piece do, and what does make manifests actually generate?
- Your status update fails with "the object has been modified; please apply your changes to the latest version." Explain the mechanism and how you fix it properly.
- Explain finalizers, and walk through what happens when one is never removed.
- How do you test an operator? Compare unit tests, envtest, and end-to-end, and be specific about what envtest cannot do.
- What do you configure before an operator is production-ready — leader election, caching, RBAC, and CRD validation?
Sign up free to read the full topic
More DevOps topics
Start free on Cariara · Coding problems · System design studio