The smallest useful operator I've ever written.
Forty lines of Go, one CRD, and a problem I'd been ignoring for two years.
The kubebuilder scaffolding for a new operator is 47 files and 1,800 lines of code before you write any logic. For two years that fact alone kept me from solving a problem that needed an operator.
Then a colleague pointed me at a tiny helper library, and I solved the problem in 40 lines.
The problem
We had a recurring class of bug: a small set of namespaces needed a specific NetworkPolicy applied to every new pod, but the policy depended on a label that wasn’t always present at create time. Manually fixing it was a one-line kubectl patch. The team did it about three times a week.
Three times a week, for two years, is around 300 patches. We are not, as a species, good at compounding annoyances.
The operator
package main
import (
"context"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrl "sigs.k8s.io/controller-runtime"
)
func main() {
mgr, _ := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
ctrl.NewControllerManagedBy(mgr).
For(&corev1.Pod{}).
Complete(reconcile.Func(func(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
// ensure the policy label; create the NetworkPolicy if missing.
return ctrl.Result{}, nil
}))
mgr.Start(ctrl.SetupSignalHandler())
}
The actual logic is boring. The lesson is that the scaffolding was the problem, not the operator. Forty lines of Go and the recurring annoyance has been gone for six months.
The lesson
If your platform team has a list of “small wins we’ll get to later,” it is almost always the scaffolding tax that is keeping them there. Find a smaller hammer.