Lab 09: Kubernetes Operator

Time: 60 minutes | Level: Architect | Docker: golang:1.22-alpine

Overview

Kubernetes operator concepts in Go: Reconciler interface, controller-runtime patterns, CRD definition (runtime.Object), reconcile loop pattern, informer/lister pattern (with fake client for testing), and operator-sdk concepts.


Step 1: Reconciler Interface

package controller

import (
	"context"
	"fmt"
	"time"

	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

// Reconciler: the core interface of every operator
type Reconciler interface {
	Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error)
}

// reconcile.Request: identifies the object to reconcile
// reconcile.Result: tells the controller when to requeue
//   Result{}: Don't requeue
//   Result{Requeue: true}: Requeue immediately
//   Result{RequeueAfter: 30*time.Second}: Requeue after 30s

// The controller-runtime calling loop:
//   1. Watch resources for changes
//   2. Enqueue NamespacedName into work queue
//   3. Call Reconcile(req) for each item
//   4. Handle Result.RequeueAfter for periodic reconciliation
//   5. Retry on error (with exponential backoff)

Step 2: Custom Resource Definition (CRD)


Step 3: Reconcile Loop Pattern


Step 4: Fake Client for Testing


Step 5: Informer and Lister Pattern


Step 6: Controller Setup with controller-runtime


Step 7: Finalizer Pattern


Step 8: Capstone — Reconciler Demo (stdlib only)

📸 Verified Output:


Summary

Concept
controller-runtime API
Notes

Reconciler

Reconcile(ctx, req) (Result, error)

Core reconcile loop

CRD

runtime.Object + DeepCopyObject

Typed k8s resource

Watch

ctrl.NewControllerManagedBy.For()

Trigger events

Owns

.Owns(&Deployment{})

Cascade reconcile

Fake client

fake.NewClientBuilder()

Unit testing

Informer

SharedInformerFactory

Local cache

Finalizer

controllerutil.AddFinalizer

Cleanup on delete

Leader election

LeaderElection: true

One active reconciler

Last updated