Guide
Kubebuilder from zero
What kubebuilder is, what it wrote in this repository, which files are yours and which you must never touch, and what to type when you want to change something. Nothing assumed: if a word is new, it is in the glossary at the end.
1. In one sentence
Kubebuilder writes the boring 80% of an operator for you, and leaves you the 20% that is your idea. The boring part is the same for every operator: the project layout, the Kubernetes YAML for the new resource, the permissions, the Dockerfile, the Makefile, the test setup. Your part is two files: what the resource looks like, and what the controller does with it.
If you have used rails new or create-react-app: same idea, for Kubernetes controllers in Go.
2. Three tools with similar names
This is the first thing that confuses everyone. There are three different things, used at three different moments:
| Tool | What it is | When you use it |
|---|---|---|
| kubebuilder | A command-line program that creates files (scaffolding). | Rarely: to start the project, to add a new kind of resource, to add a plugin. It is not needed to build or run anything. |
| controller-gen | A program that reads special comments in your Go code (markers) and writes YAML and Go from them. | Every time you change the types or the permissions, through make manifests generate. The Makefile downloads it into bin/. |
| controller-runtime | A Go library: the engine of the operator (watching objects, the queue, calling your code, metrics, leader election). | All the time, without noticing: it is imported by cmd/main.go and the controller, and runs inside the operator. |
Kubebuilder writes code that uses controller-runtime, and a Makefile that runs controller-gen. After the first day you mostly forget kubebuilder exists.
3. How this repository was started
Two commands made the skeleton. You never need to run them again; they are here so you know where everything came from.
kubebuilder init --domain allan-nava.github.io --repo github.com/Allan-Nava/streamprobe-operator
kubebuilder create api --group streaming --version v1alpha1 --kind StreamProbe --resource --controller
initmade the project:cmd/main.go, the Makefile, the Dockerfile,config/with the deployment YAML, the test setup, the CI workflows.create apimade the new resource: its type inapi/v1alpha1/streamprobe_types.go, an empty controller ininternal/controller/streamprobe_controller.go, and a test.
The three words of the second command build the resource's name. Group streaming + domain allan-nava.github.io = the API group streaming.allan-nava.github.io. Version v1alpha1 says "early, may change". Kind StreamProbe is the name you write in YAML. Together they make the apiVersion and kind at the top of every StreamProbe:
apiVersion: streaming.allan-nava.github.io/v1alpha1
kind: StreamProbe
The file PROJECT at the root is kubebuilder's own notebook of what it created. It says "DO NOT EDIT", and it means it.
4. Your files and generated files
The single most important thing to learn. Some files you write; some are generated from yours and get overwritten. Editing a generated file is wasted work: the next make puts it back.
| Path | Who writes it | What it is |
|---|---|---|
api/v1alpha1/streamprobe_types.go | You | The shape of a StreamProbe: spec and status, plus markers. |
internal/controller/*.go | You | What happens to a StreamProbe: the reconcile loop. |
internal/hls/, internal/probe/ | You | Plain Go, nothing to do with kubebuilder. |
config/samples/ | You | Example StreamProbes. |
api/v1alpha1/zz_generated.deepcopy.go | Generated (make generate) | Copy functions every Kubernetes type needs. |
config/crd/bases/*.yaml | Generated (make manifests) | The CRD: what the API server knows about StreamProbe. |
config/rbac/role.yaml | Generated (make manifests) | The operator's permissions. |
dist/chart/ | Generated (helm plugin), then adjusted | The Helm chart; see plugins. |
cmd/main.go, Makefile, Dockerfile, the rest of config/ | Scaffolded once, then yours | Written by kubebuilder on day one; edit them when you need to (the prober is wired in main.go). |
A trick to tell them apart: generated files have a name starting with zz_, or sit in config/crd/bases and config/rbac/role.yaml, or say "Code generated … DO NOT EDIT" at the top.
5. Markers: comments that write YAML
A marker is a Go comment that starts with // +. Go ignores it; controller-gen reads it and turns it into YAML. This is how the Go type becomes the rules the API server enforces.
// interval is how often the stream is checked.
// +kubebuilder:default="30s"
// +optional
Interval metav1.Duration `json:"interval,omitzero"`
That comment becomes, in the CRD, "the field interval is optional and, if missing, is 30s". The API server fills it in before anyone sees the object. The ones used here:
| Marker | Where | Effect |
|---|---|---|
+required / +optional | a field | Must be present / may be missing. |
+kubebuilder:default=… | a field | Value when missing. |
+kubebuilder:validation:Pattern=… | a field | A regular expression the value must match (the URL must start with http). |
+kubebuilder:validation:MaxLength=… | a field | Longest allowed string. |
+kubebuilder:subresource:status | the type | The status is written separately from the spec. |
+kubebuilder:printcolumn:… | the type | A column in kubectl get. |
+kubebuilder:resource:shortName=sp | the type | kubectl get sp works. |
+kubebuilder:rbac:groups=…,resources=…,verbs=… | the controller | A permission in role.yaml. |
The full list is in the kubebuilder book. A marker with a typo is silently ignored, so check the generated YAML after adding one.
6. The everyday loop
Almost every change follows the same four steps:
1. edit api/…_types.go or internal/controller/… # your files
2. generate make manifests generate # CRD, RBAC, DeepCopy from the markers
3. test make test (and make lint) # unit tests + envtest, no cluster needed
4. try make install run # CRD into a real cluster, controller on your laptop
Step 4 needs a cluster (kind on a laptop is enough). make run runs the controller as a normal program on your machine, talking to the cluster: you see its logs in the terminal and stop it with Ctrl+C. Nothing is built into an image. When it works, commit your files and the generated ones together.
7. Recipe: add a field to the spec
Say a StreamProbe should accept a user agent to send to the origin. From start to finish:
- The type. In
api/v1alpha1/streamprobe_types.go, insideStreamProbeSpec:
The comment above the field becomes its description in// userAgent is sent with every request; empty means the operator's own. // +kubebuilder:validation:MaxLength=256 // +optional UserAgent string `json:"userAgent,omitempty"`kubectl explain streamprobe.spec.userAgent. Thejson:"…"tag is the name in YAML. - Generate.
make manifests generate. Look at the diff ofconfig/crd/bases/…yaml: the new field is there with its rule. - Use it. In the controller, read
sp.Spec.UserAgentand pass it to the prober. - Test it. A case in the envtest suite that sets the field;
make test. - Document it. A row in the reference and the README.
- Ship the CRD. In a real cluster the CRD must be updated (
make install, or the chart after regenerating it) before anyone uses the field. See the first mistake below for why.
8. Recipe: let the controller read something new
The operator may only do what its ServiceAccount is allowed to. Say it must read Secrets (for a token in the spec):
- Above
Reconcile, add a marker:// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watchgroups=""is the core group (Pods, Secrets, ConfigMaps live there). make manifests: the permission appears inconfig/rbac/role.yaml.- Use it in the code. Never write a Role by hand for the operator: the next
make manifestswould not know about it.
9. The make targets you will use
make help lists them all. The ones that matter:
| Command | What it does | Needs a cluster? |
|---|---|---|
make manifests | CRD and RBAC YAML from the markers. | No |
make generate | The zz_generated Go code. | No |
make test | Runs manifests, generate, fmt, vet, then all tests with envtest. | No |
make lint | golangci-lint. | No |
make install / uninstall | Puts the CRD in the cluster / removes it (and every StreamProbe with it). | Yes |
make run | The controller on your machine, against the cluster. | Yes |
make deploy / undeploy | The controller inside the cluster, from the image in IMG. | Yes |
make docker-build | The image, from the Dockerfile. | No (needs Docker) |
make test-e2e | Creates a kind cluster, runs the end-to-end suite in it, deletes it. Needs kind and Docker installed. | Makes its own |
make build-installer | dist/install.yaml: everything in one file. | No |
The first time, make downloads its tools into bin/ (controller-gen, kustomize, envtest binaries, golangci-lint): a few hundred MB, ignored by git.
10. envtest, in plain words
Testing a controller needs an API server to talk to. A whole cluster is slow and heavy. envtest starts only the two programs that make up the API: kube-apiserver and etcd (its database), as plain processes, for the duration of the tests. There are no nodes, so no Pods ever run; but objects can be created, read, validated and watched exactly as in a real cluster.
That is why the tests here check the CRD's defaults and validation for real, and run the reconcile loop against a real API, in a few seconds, without Docker. make setup-envtest downloads the binaries; make test does it for you.
11. Plugins: the Helm chart
Kubebuilder can add things later through plugins. This repository used one:
kubebuilder edit --plugins=helm/v2-alpha
It turned the YAML in config/ into a Helm chart in dist/chart/ and added the helm-* make targets. The chart is a copy: when config/ changes (a new field in the CRD, a new permission), run the command again to bring the chart up to date, then check that our own changes to the chart survived (listed in CLAUDE.md: the empty image tag, the chart metadata, the alerts).
12. The usual mistakes, and how they look
| Mistake | What you see | Fix |
|---|---|---|
| New field in Go, CRD not regenerated or not installed | The field disappears: you apply it, kubectl get -o yaml does not show it. The API server drops fields its schema does not know ("pruning"), without an error. | make manifests, then make install. |
| Missing rbac marker | The controller logs forbidden: … cannot get resource. | Add the marker, make manifests, redeploy. |
| Edited a generated file | Your change vanishes at the next make. | Change the marker or the Go type instead. |
Writing the status with Update instead of Status().Update | The status never changes: with the status subresource, a normal update ignores it. | r.Status().Update(ctx, &obj). |
| Reacting to your own status writes | The controller reconciles in a tight loop, logs fill up. | Filter the watch (GenerationChangedPredicate), as here. |
Changed Reconcile, forgot that it can run any time | Duplicate work after a restart, or nothing after a missed event. | Decide from what the object says now, not from what woke you up. |
13. Glossary
- CRD (CustomResourceDefinition)
- The YAML that teaches the API server a new kind of object, with its schema. Here:
streamprobes.streaming.allan-nava.github.io. - CR (custom resource)
- One object of that kind: one StreamProbe.
- Controller
- A program that watches objects and acts on them. Here:
StreamProbeReconciler. - Reconcile
- The function called with the name of an object that may need attention. It reads the object and makes the world match it.
- Manager
- The process that hosts the controllers:
cmd/main.gocreates it. It also serves health checks and metrics, and does leader election. - Leader election
- With two replicas of the operator, only one works at a time; the other waits to take over.
- Scheme
- The list of Go types the client knows how to turn into JSON and back.
AddToSchemeadds StreamProbe to it. - DeepCopy
- Generated functions that copy an object completely, needed because the client caches objects and must not share them.
- kustomize
- A tool that assembles YAML from a base plus patches;
config/is a kustomize tree. Built intokubectlaskubectl apply -k. - kind
- Kubernetes in Docker: a whole cluster in containers on your laptop, used by the end-to-end tests.
- envtest
- An API server and etcd started by the tests, without nodes. See above.
- Marker
- A
// +…comment read by controller-gen. See above. - Status subresource
- The status written through its own endpoint, so users and the controller do not overwrite each other, and a status write does not count as a spec change.
- Generation / observedGeneration
- A counter the API server increases on every spec change; the controller writes the one it last handled into the status.