Stage 9, Part 2 of 9, Cluster Extensibility (CRDs, Controllers, Operators)

Text

PART 2: ADVANCED CONCEPTS

5. Admission Webhooks

Admission webhooks intercept API requests before objects are persisted. They are the enforcement layer for policies.

The Three Webhook Types

TypePurposeCan Modify?Order
MutatingModify objects✅ YesFirst
ValidatingAllow/deny❌ NoSecond
ConversionConvert between CRD versions✅ YesDuring read/write

The Admission Flow

text
API Request
    │
    ▼
Authentication (Who are you?)
    │
    ▼
Authorization (What can you do?)
    │
    ▼
Mutating Admission (Modify the object)
    │
    ▼
Schema Validation (OpenAPI)
    │
    ▼
Validating Admission (Allow or deny)
    │
    ▼
Persist to etcd

Validating Webhook Example

yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: webapp-validator
webhooks:
- name: validate.webapp.example.com
  clientConfig:
    service:
      name: webhook-service
      namespace: webhook-system
      path: /validate
    caBundle: <base64-ca>
  rules:
  - operations: ["CREATE", "UPDATE"]
    apiGroups: ["example.com"]
    apiVersions: ["v1"]
    resources: ["webapps"]
  admissionReviewVersions: ["v1"]
  sideEffects: None
  failurePolicy: Fail
  timeoutSeconds: 10

Mutating Webhook Example

yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: webapp-mutator
webhooks:
- name: mutate.webapp.example.com
  clientConfig:
    service:
      name: webhook-service
      namespace: webhook-system
      path: /mutate
    caBundle: <base64-ca>
  rules:
  - operations: ["CREATE"]
    apiGroups: ["example.com"]
    apiVersions: ["v1"]
    resources: ["webapps"]
  admissionReviewVersions: ["v1"]
  sideEffects: None
  failurePolicy: Fail
  timeoutSeconds: 10

ValidatingAdmissionPolicy (GA in 1.32)

Kubernetes now ships a built-in, in-process policy mechanism that needs no external webhook. ValidatingAdmissionPolicy reached GA in v1.30.

yaml
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: require-labels
spec:
  matchConstraints:
    resourceRules:
    - apiGroups: ["example.com"]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["webapps"]
  validations:
  - expression: "object.metadata.labels.exists(l, l == 'team')"
    message: "All WebApps must have a 'team' label"

MutatingAdmissionPolicy (Beta in 1.33)

MutatingAdmissionPolicy entered beta in 1.33, enabling in-process mutation.

What Belongs Where in 2026

Policy TypeWhere to Put It
Required labelsValidatingAdmissionPolicy (CEL)
Registry allowlistsValidatingAdmissionPolicy (CEL)
Resource limitsValidatingAdmissionPolicy (CEL)
Privileged container banValidatingAdmissionPolicy (CEL)
Image signature verificationValidating Webhook (external lookup)
Sidecar injectionMutating Webhook
Image digest pinningMutating Webhook

The latency improvement of CEL-based policies is real: in-process CEL evaluation runs in microseconds versus tens of milliseconds for a webhook round trip, and you eliminate the webhook availability dependency.

Webhook Failure Policy

PolicyBehaviorWhen to Use
FailReject if webhook unreachableSecurity-critical
IgnoreAllow if webhook unreachableOptional features

The Recovery Pattern

If a webhook is blocking cluster recovery:

bash
kubectl patch validatingwebhookconfiguration <name> --type='json' \
  -p='[{"op":"replace","path":"/webhooks/0/failurePolicy","value":"Ignore"}]'

⚠️ This disables enforcement. Use only during confirmed outages.


6. Operator SDK and Kubebuilder

Kubebuilder and Operator SDK are the standard frameworks for building operators.

Kubebuilder Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                    KUBEBUILDER ARCHITECTURE                 │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  Generated Code                                     │   │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐ │   │
│  │  │ API Types   │  │ Controllers │  │ Config      │ │   │
│  │  │ (CRD)       │  │ (Reconcile) │  │ (Kustomize) │ │   │
│  │  └─────────────┘  └─────────────┘  └─────────────┘ │   │
│  └─────────────────────────────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  controller-runtime                                 │   │
│  │  • Manager (lifecycle)                              │   │
│  │  • Client (CRUD)                                    │   │
│  │  • Cache (Informer)                                 │   │
│  │  • Webhook server                                   │   │
│  └─────────────────────────────────────────────────────┘   │
│                         │                                   │
│                         ▼                                   │
│  ┌─────────────────────────────────────────────────────┐   │
│  │  client-go                                          │   │
│  │  • REST client                                      │   │
│  │  • Informers                                        │   │
│  │  • Workqueues                                       │   │
│  └─────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Kubebuilder Workflow

bash
# 1. Initialize project
kubebuilder init --domain example.com --repo github.com/myorg/myoperator

# 2. Create API (CRD + Controller)
kubebuilder create api --group webapp --version v1 --kind WebApp

# 3. Define types in api/v1/webapp_types.go

# 4. Implement reconcile logic in controllers/webapp_controller.go

# 5. Generate CRDs
make manifests

# 6. Install CRDs
make install

# 7. Run controller locally
make run

# 8. Deploy to cluster
make docker-build docker-push IMG=myregistry/myoperator:v1
make deploy IMG=myregistry/myoperator:v1

The API Types

go
// api/v1/webapp_types.go
type WebAppSpec struct {
    Image    string `json:"image"`
    Replicas int32  `json:"replicas,omitempty"`
    Port     int32  `json:"port,omitempty"`
}

type WebAppStatus struct {
    AvailableReplicas int32              `json:"availableReplicas,omitempty"`
    Conditions        []metav1.Condition `json:"conditions,omitempty"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status
type WebApp struct {
    metav1.TypeMeta   `json:",inline"`
    metav1.ObjectMeta `json:"metadata,omitempty"`
    Spec   WebAppSpec   `json:"spec,omitempty"`
    Status WebAppStatus `json:"status,omitempty"`
}

Kubebuilder Markers

MarkerPurpose
+kubebuilder:subresource:statusEnable status subresource
+kubebuilder:subresource:scaleEnable scale subresource
+kubebuilder:validation:Minimum=1Minimum value
+kubebuilder:validation:Maximum=100Maximum value
+kubebuilder:default=1Default value
+kubebuilder:printcolumnAdditional printer columns
+kubebuilder:webhookGenerate webhook config

Operator SDK vs Kubebuilder

AspectOperator SDKKubebuilder
MaintainerRed HatKubernetes SIG
Corecontroller-runtimecontroller-runtime
CLIoperator-sdkkubebuilder
ScaffoldingMore optionsSimpler
OLMBuilt-inAdd-on
Best ForEnterprise, OLMGeneral purpose

Both frameworks use controller-runtime under the hood. The choice is mostly about tooling preference.


7. CRD Versioning and Conversion

CRDs support multiple versions, enabling safe API evolution.

Multiple Versions

yaml
spec:
  versions:
  - name: v1alpha1
    served: true
    storage: false
    schema:
      openAPIV3Schema: ...
  - name: v1
    served: true
    storage: true        # Only one storage version
    schema:
      openAPIV3Schema: ...

Storage vs Served Versions

SettingMeaning
served: trueAPI accepts this version
storage: truePrimary storage version (exactly one)

Conversion Webhooks

When multiple versions exist, conversion webhooks convert between versions.

yaml
spec:
  conversion:
    strategy: Webhook
    webhook:
      clientConfig:
        service:
          name: webhook-service
          namespace: webhook-system
          path: /convert
      conversionReviewVersions: ["v1"]

The Hub-and-Spoke Pattern

In conversion, one version is the hub (storage version), and others are spokes.

text
v1alpha1 ──► v1 (hub) ◄── v1beta1

Each spoke converts to/from the hub.

go
// Hub marks v1 as the hub
func (*WebApp) Hub() {}

// ConvertTo converts v1 to v1alpha1
func (src *WebApp) ConvertTo(dstRaw conversion.Hub) error {
    dst := dstRaw.(*v1alpha1.WebApp)
    // Conversion logic
    return nil
}

// ConvertFrom converts v1alpha1 to v1
func (dst *WebApp) ConvertFrom(srcRaw conversion.Hub) error {
    src := srcRaw.(*v1alpha1.WebApp)
    // Conversion logic
    return nil
}

CRD Versioning Best Practices

PracticeWhy
Start with v1alpha1Signal instability
Graduate to v1Stable API
Never change v1 schemaCompatibility
Use conversion webhooksMulti-version support
Test conversion pathsPrevent data loss

8. Finalizers and OwnerReferences

Finalizers

A finalizer is a marker that prevents an object from being deleted until cleanup is complete.

yaml
metadata:
  finalizers:
  - example.com/cleanup

Flow:

  1. User deletes object
  2. Object is marked deletionTimestamp
  3. Controller sees finalizer, performs cleanup
  4. Controller removes finalizer
  5. Object is deleted
go
const myFinalizer = "example.com/cleanup"

func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    var webapp examplev1.WebApp
    if err := r.Get(ctx, req.NamespacedName, &webapp); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    if webapp.DeletionTimestamp.IsZero() {
        // Not being deleted — add finalizer if missing
        if !controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
            controllerutil.AddFinalizer(&webapp, myFinalizer)
            if err := r.Update(ctx, &webapp); err != nil {
                return ctrl.Result{}, err
            }
        }
    } else {
        // Being deleted — run cleanup
        if controllerutil.ContainsFinalizer(&webapp, myFinalizer) {
            // Cleanup external resources
            if err := r.cleanupExternal(&webapp); err != nil {
                return ctrl.Result{}, err
            }
            controllerutil.RemoveFinalizer(&webapp, myFinalizer)
            if err := r.Update(ctx, &webapp); err != nil {
                return ctrl.Result{}, err
            }
        }
        return ctrl.Result{}, nil
    }

    return ctrl.Result{}, nil
}

OwnerReferences

OwnerReferences enable cascading deletion. When a parent is deleted, children are garbage collected.

yaml
metadata:
  ownerReferences:
  - apiVersion: example.com/v1
    kind: WebApp
    name: my-webapp
    uid: <uid>
    controller: true
    blockOwnerDeletion: true
go
// Set owner reference
if err := ctrl.SetControllerReference(&webapp, &deployment, r.Scheme); err != nil {
    return ctrl.Result{}, err
}

9. Server-Side Apply (SSA) for Operators

Server-Side Apply is the modern way for operators to manage resources.

Why SSA

Client-Side ApplyServer-Side Apply
Uses last-applied annotationUses managedFields
Whole-resource conflictsField-level conflicts
Hard with multiple controllersNatural multi-controller

Using SSA in Operators

go
import (
    "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    "sigs.k8s.io/controller-runtime/pkg/client"
)

func (r *WebAppReconciler) applyDeployment(ctx context.Context, webapp *examplev1.WebApp) error {
    deployment := &appsv1.Deployment{
        TypeMeta: metav1.TypeMeta{
            APIVersion: "apps/v1",
            Kind:       "Deployment",
        },
        ObjectMeta: metav1.ObjectMeta{
            Name:      webapp.Name,
            Namespace: webapp.Namespace,
        },
        Spec: r.deploymentSpec(webapp),
    }

    // Set owner reference
    ctrl.SetControllerReference(webapp, deployment, r.Scheme)

    // Server-Side Apply
    return r.Patch(ctx, deployment, client.Apply, client.ForceOwnership, client.FieldOwner("webapp-controller"))
}

SSA Benefits for Operators

BenefitWhy
Field ownershipKnow which controller owns which field
Conflict detectionDetect when another controller modifies your fields
Multi-controllerMultiple controllers can manage the same resource
IdempotentApply is naturally idempotent

10. Operator Lifecycle Manager (OLM)

OLM manages the lifecycle of operators in a cluster.

OLM Components

ComponentPurpose
OLM OperatorManages CSV lifecycle
Catalog OperatorResolves dependencies
CatalogSourceSource of operator bundles
SubscriptionRequest to install an operator
ClusterServiceVersion (CSV)Operator metadata
InstallPlanStep-by-step installation

Installing an Operator with OLM

yaml
apiVersion: operators.coreos.com/v1alpha1
kind: Subscription
metadata:
  name: my-operator
  namespace: operators
spec:
  channel: stable
  name: my-operator
  source: my-catalog
  sourceNamespace: olm

OLM Benefits

BenefitWhy
Dependency resolutionAutomatically installs CRDs
UpgradesSafe operator upgrades
Multi-tenancyOperator scoping
CatalogDiscoverable operators

11. Metrics, Logging, and Tracing for Operators

Prometheus Metrics

go
import (
    "github.com/prometheus/client_golang/prometheus"
    "sigs.k8s.io/controller-runtime/pkg/metrics"
)

var (
    reconcileTotal = prometheus.NewCounterVec(
        prometheus.CounterOpts{
            Name: "webapp_reconcile_total",
            Help: "Total number of reconciliations",
        },
        []string{"result"},
    )
    reconcileDuration = prometheus.NewHistogramVec(
        prometheus.HistogramOpts{
            Name:    "webapp_reconcile_duration_seconds",
            Help:    "Duration of reconciliations",
            Buckets: prometheus.DefBuckets,
        },
        []string{"result"},
    )
)

func init() {
    metrics.Registry.MustRegister(reconcileTotal, reconcileDuration)
}

Structured Logging

go
import "github.com/go-logr/logr"

func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    log := log.FromContext(ctx)

    log.Info("Reconciling WebApp", "name", req.Name, "namespace", req.Namespace)

    // ...

    log.V(1).Info("Deployment created", "name", deployment.Name)

    return ctrl.Result{}, nil
}

Distributed Tracing

go
import (
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/trace"
)

var tracer = otel.Tracer("webapp-controller")

func (r *WebAppReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    ctx, span := tracer.Start(ctx, "Reconcile")
    defer span.End()

    // ...

    return ctrl.Result{}, nil
}

12. Testing Operators

The Testing Pyramid

LevelToolPurpose
UnitGo testingIndividual functions
IntegrationenvtestController against real API server
E2EKUTTLFull cluster scenarios
FuzzingGo fuzzingCRD input validation

envtest

envtest starts a real API server and etcd for testing.

go
func TestReconcile(t *testing.T) {
    // Setup envtest
    testEnv := &envtest.Environment{
        CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
    }
    cfg, err := testEnv.Start()
    require.NoError(t, err)
    defer testEnv.Stop()

    // Create client
    k8sClient, err := client.New(cfg, client.Options{Scheme: scheme})
    require.NoError(t, err)

    // Create reconciler
    reconciler := &WebAppReconciler{
        Client: k8sClient,
        Scheme: k8sClient.Scheme(),
    }

    // Create test resource
    webapp := &examplev1.WebApp{
        ObjectMeta: metav1.ObjectMeta{
            Name:      "test",
            Namespace: "default",
        },
        Spec: examplev1.WebAppSpec{
            Image:    "nginx:1.25",
            Replicas: 3,
        },
    }
    require.NoError(t, k8sClient.Create(context.Background(), webapp))

    // Reconcile
    _, err = reconciler.Reconcile(context.Background(), ctrl.Request{
        NamespacedName: types.NamespacedName{
            Name:      "test",
            Namespace: "default",
        },
    })
    require.NoError(t, err)

    // Verify deployment created
    var deployment appsv1.Deployment
    err = k8sClient.Get(context.Background(), types.NamespacedName{
        Name:      "test",
        Namespace: "default",
    }, &deployment)
    require.NoError(t, err)
    assert.Equal(t, int32(3), *deployment.Spec.Replicas)
}

KUTTL

KUTTL (Kubernetes Test Tool) runs declarative E2E tests.

yaml
# kuttl-test.yaml
apiVersion: kuttl.dev/v1beta1
kind: TestSuite
testDirs:
- ./tests/e2e
yaml
# tests/e2e/webapp/00-create.yaml
apiVersion: example.com/v1
kind: WebApp
metadata:
  name: test-webapp
spec:
  image: nginx:1.25
  replicas: 3
yaml
# tests/e2e/webapp/00-assert.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test-webapp
spec:
  replicas: 3

Fuzzing

Go fuzzing tests CRD input validation.

go
func FuzzWebAppSpec(f *testing.F) {
    f.Add("nginx:1.25", int32(3), int32(8080))
    f.Fuzz(func(t *testing.T, image string, replicas int32, port int32) {
        spec := WebAppSpec{
            Image:    image,
            Replicas: replicas,
            Port:     port,
        }
        // Validate spec
        if err := spec.Validate(); err != nil {
            // Expected for invalid input
        }
    })
}

13. Common Operators

Prometheus Operator

CRDPurpose
PrometheusPrometheus instance
AlertmanagerAlertmanager instance
ServiceMonitorScrape configuration
PodMonitorPod scrape configuration
PrometheusRuleAlerting rules

cert-manager

CRDPurpose
CertificateTLS certificate request
IssuerNamespace-scoped CA
ClusterIssuerCluster-scoped CA
CertificateRequestActual CSR

Istio Operator

CRDPurpose
IstioOperatorIstio installation config
VirtualServiceTraffic routing
DestinationRuleLoad balancing
GatewayIngress/egress

1:1 copy of the class Google Doc, code in code blocks.