Skip to content
streamprobe

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:

ToolWhat it isWhen you use it
kubebuilderA 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-genA 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-runtimeA 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

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.

PathWho writes itWhat it is
api/v1alpha1/streamprobe_types.goYouThe shape of a StreamProbe: spec and status, plus markers.
internal/controller/*.goYouWhat happens to a StreamProbe: the reconcile loop.
internal/hls/, internal/probe/YouPlain Go, nothing to do with kubebuilder.
config/samples/YouExample StreamProbes.
api/v1alpha1/zz_generated.deepcopy.goGenerated (make generate)Copy functions every Kubernetes type needs.
config/crd/bases/*.yamlGenerated (make manifests)The CRD: what the API server knows about StreamProbe.
config/rbac/role.yamlGenerated (make manifests)The operator's permissions.
dist/chart/Generated (helm plugin), then adjustedThe Helm chart; see plugins.
cmd/main.go, Makefile, Dockerfile, the rest of config/Scaffolded once, then yoursWritten 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:

MarkerWhereEffect
+required / +optionala fieldMust be present / may be missing.
+kubebuilder:default=…a fieldValue when missing.
+kubebuilder:validation:Pattern=…a fieldA regular expression the value must match (the URL must start with http).
+kubebuilder:validation:MaxLength=…a fieldLongest allowed string.
+kubebuilder:subresource:statusthe typeThe status is written separately from the spec.
+kubebuilder:printcolumn:…the typeA column in kubectl get.
+kubebuilder:resource:shortName=spthe typekubectl get sp works.
+kubebuilder:rbac:groups=…,resources=…,verbs=…the controllerA 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:

  1. The type. In api/v1alpha1/streamprobe_types.go, inside StreamProbeSpec:
    // userAgent is sent with every request; empty means the operator's own.
    // +kubebuilder:validation:MaxLength=256
    // +optional
    UserAgent string `json:"userAgent,omitempty"`
    The comment above the field becomes its description in kubectl explain streamprobe.spec.userAgent. The json:"…" tag is the name in YAML.
  2. Generate. make manifests generate. Look at the diff of config/crd/bases/…yaml: the new field is there with its rule.
  3. Use it. In the controller, read sp.Spec.UserAgent and pass it to the prober.
  4. Test it. A case in the envtest suite that sets the field; make test.
  5. Document it. A row in the reference and the README.
  6. 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):

  1. Above Reconcile, add a marker:
    // +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
    groups="" is the core group (Pods, Secrets, ConfigMaps live there).
  2. make manifests: the permission appears in config/rbac/role.yaml.
  3. Use it in the code. Never write a Role by hand for the operator: the next make manifests would not know about it.

9. The make targets you will use

make help lists them all. The ones that matter:

CommandWhat it doesNeeds a cluster?
make manifestsCRD and RBAC YAML from the markers.No
make generateThe zz_generated Go code.No
make testRuns manifests, generate, fmt, vet, then all tests with envtest.No
make lintgolangci-lint.No
make install / uninstallPuts the CRD in the cluster / removes it (and every StreamProbe with it).Yes
make runThe controller on your machine, against the cluster.Yes
make deploy / undeployThe controller inside the cluster, from the image in IMG.Yes
make docker-buildThe image, from the Dockerfile.No (needs Docker)
make test-e2eCreates a kind cluster, runs the end-to-end suite in it, deletes it. Needs kind and Docker installed.Makes its own
make build-installerdist/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

MistakeWhat you seeFix
New field in Go, CRD not regenerated or not installedThe 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 markerThe controller logs forbidden: … cannot get resource.Add the marker, make manifests, redeploy.
Edited a generated fileYour change vanishes at the next make.Change the marker or the Go type instead.
Writing the status with Update instead of Status().UpdateThe status never changes: with the status subresource, a normal update ignores it.r.Status().Update(ctx, &obj).
Reacting to your own status writesThe controller reconciles in a tight loop, logs fill up.Filter the watch (GenerationChangedPredicate), as here.
Changed Reconcile, forgot that it can run any timeDuplicate 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.go creates 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. AddToScheme adds 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 into kubectl as kubectl 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.