Cloud Native 20 min read

Build Your First Kubernetes Operator with Kubebuilder: A Step‑by‑Step Guide

This tutorial walks you through the concepts of Kubernetes Operators, how they work, and provides a hands‑on walkthrough using Kubebuilder to set up the development environment, create a simple Foo operator, define CRDs, implement controller logic, and deploy and test the operator on a local cluster.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build Your First Kubernetes Operator with Kubebuilder: A Step‑by‑Step Guide

What is an Operator?

Kubernetes operators extend the native resources of a cluster by embedding custom logic that automates tasks beyond the capabilities of standard Kubernetes objects. They translate engineers' operational knowledge into code, enabling automation of complex workflows such as deploying and managing services like MySQL, Elasticsearch, or GitLab Runner.

Building an Operator

Set up development environment

Go v1.17.9+

Docker 17.03+

kubectl v1.11.3+

A Kubernetes v1.11.3+ cluster (Kind is recommended for a local cluster)

Install Kubebuilder:

curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH) && chmod +x kubebuilder && mv kubebuilder /usr/local/bin/

Verify the installation:

kubebuilder version
Version: main.version{KubeBuilderVersion:"3.4.1", KubernetesVendor:"1.23.5", GitCommit:"d59d7882ce95ce5de10238e135ddff31d8ede026", BuildDate:"2022-05-06T13:58:56Z", GoOs:"darwin", GoArch:"amd64"}

Build a simple Operator

Initialize a new project (this will download controller‑runtime and scaffold the project):

kubebuilder init --domain my.domain --repo my.domain/tutorial
Writing kustomize manifests for you to edit...
Writing scaffold for you to edit...
Get controller runtime:
$ go get sigs.k8s.io/[email protected]
...

Project structure (Go project):

ls -a
.dockerignore
.gitignore
Dockerfile
Makefile
PROJECT
README.md
config/
go.mod
go.sum
hack/
main.go

Key components:

main.go – entry point that sets up and runs the manager.

config/ – manifests for deploying the operator to Kubernetes.

Dockerfile – builds the manager image.

The operator consists of a Custom Resource Definition (CRD) and a controller.

Custom CRD and Controller

Define the Foo CRD (spec includes a name field, status includes a happy boolean):

package v1

import (
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// FooSpec defines the desired state of Foo
type FooSpec struct {
    // Name of the friend Foo is looking for
    Name string `json:"name"`
}

// FooStatus defines the observed state of Foo
type FooStatus struct {
    // Happy will be set to true if Foo found a friend
    Happy bool `json:"happy,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status

// Foo is the Schema for the foos API
type Foo struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`

    Spec   FooSpec   `json:"spec,omitempty"`
    Status FooStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true

// FooList contains a list of Foo
type FooList struct {
    metav1.TypeMeta `json:",inline"`
    metav1.ListMeta `json:"metadata,omitempty"`
    Items           []Foo `json:"items"`
}

func init() {
    SchemeBuilder.Register(&Foo{}, &FooList{})
}

Implement the controller logic (reconciliation watches Foo resources and Pods, updates the happy status based on whether a Pod with the same name exists):

package controllers

import (
    "context"
    corev1 "k8s.io/api/core/v1"
    "k8s.io/apimachinery/pkg/runtime"
    "k8s.io/apimachinery/pkg/types"
    ctrl "sigs.k8s.io/controller-runtime"
    "sigs.k8s.io/controller-runtime/pkg/client"
    "sigs.k8s.io/controller-runtime/pkg/handler"
    "sigs.k8s.io/controller-runtime/pkg/log"
    "sigs.k8s.io/controller-runtime/pkg/reconcile"
    "sigs.k8s.io/controller-runtime/pkg/source"

    tutorialv1 "my.domain/tutorial/api/v1"
)

type FooReconciler struct {
    client.Client
    Scheme *runtime.Scheme
}

//+kubebuilder:rbac:groups=tutorial.my.domain,resources=foos,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=tutorial.my.domain,resources=foos/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=tutorial.my.domain,resources=foos/finalizers,verbs=update
//+kubebuilder:rbac:groups="",resources=pods,verbs=get;list;watch

func (r *FooReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    log := log.FromContext(ctx)
    log.Info("reconciling foo custom resource")

    var foo tutorialv1.Foo
    if err := r.Get(ctx, req.NamespacedName, &foo); err != nil {
        log.Error(err, "unable to fetch Foo")
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    var podList corev1.PodList
    var friendFound bool
    if err := r.List(ctx, &podList); err != nil {
        log.Error(err, "unable to list pods")
    } else {
        for _, item := range podList.Items {
            if item.GetName() == foo.Spec.Name {
                log.Info("pod linked to a foo custom resource found", "name", item.GetName())
                friendFound = true
            }
        }
    }

    foo.Status.Happy = friendFound
    if err := r.Status().Update(ctx, &foo); err != nil {
        log.Error(err, "unable to update foo's happy status", "status", friendFound)
        return ctrl.Result{}, err
    }
    log.Info("foo's happy status updated", "status", friendFound)
    log.Info("foo custom resource reconciled")
    return ctrl.Result{}, nil
}

func (r *FooReconciler) SetupWithManager(mgr ctrl.Manager) error {
    return ctrl.NewControllerManagedBy(mgr).
        For(&tutorialv1.Foo{}).
        Watches(&source.Kind{Type: &corev1.Pod{}}, handler.EnqueueRequestsFromMapFunc(r.mapPodsReqToFooReq)).
        Complete(r)
}

func (r *FooReconciler) mapPodsReqToFooReq(obj client.Object) []reconcile.Request {
    ctx := context.Background()
    log := log.FromContext(ctx)
    req := []reconcile.Request{}
    var list tutorialv1.FooList
    if err := r.Client.List(context.TODO(), &list); err != nil {
        log.Error(err, "unable to list foo custom resources")
    } else {
        for _, item := range list.Items {
            if item.Spec.Name == obj.GetName() {
                req = append(req, reconcile.Request{NamespacedName: types.NamespacedName{Name: item.Name, Namespace: item.Namespace}})
                log.Info("pod linked to a foo custom resource issued an event", "name", obj.GetName())
            }
        }
    }
    return req
}

Two diagrams illustrate the CRD and controller architecture:

CRD diagram
CRD diagram
Controller diagram
Controller diagram

Run the Controller

Install the CRD into the cluster and start the manager:

make install
kubectl apply -k config/crd
make run

The manager starts, followed by the Foo controller, which begins watching events.

Test the Controller

Create two Foo custom resources and a Pod named jack to see the controller update the happy status when a matching Pod exists:

apiVersion: tutorial.my.domain/v1
kind: Foo
metadata:
  name: foo-01
spec:
  name: jack
---
apiVersion: tutorial.my.domain/v1
kind: Foo
metadata:
  name: foo-02
spec:
  name: joe

kubectl apply -f config/samples

After deploying the jack Pod, the controller logs show the reconciliation loop updating foo-01 's status to true. Updating foo-02 to reference jack also triggers a successful reconciliation.

Further Work

Potential improvements include optimizing event filtering, refining RBAC permissions, enhancing logging, emitting Kubernetes events on updates, extending the Foo CRD with additional fields, and adding unit and end‑to‑end tests.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

KubernetesOperatorGoControllerCRDKubebuilder
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.