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
| Type | Purpose | Can Modify? | Order |
| Mutating | Modify objects | ✅ Yes | First |
| Validating | Allow/deny | ❌ No | Second |
| Conversion | Convert between CRD versions | ✅ Yes | During 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 Type | Where to Put It |
| Required labels | ValidatingAdmissionPolicy (CEL) |
| Registry allowlists | ValidatingAdmissionPolicy (CEL) |
| Resource limits | ValidatingAdmissionPolicy (CEL) |
| Privileged container ban | ValidatingAdmissionPolicy (CEL) |
| Image signature verification | Validating Webhook (external lookup) |
| Sidecar injection | Mutating Webhook |
| Image digest pinning | Mutating 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
| Policy | Behavior | When to Use |
| Fail | Reject if webhook unreachable | Security-critical |
| Ignore | Allow if webhook unreachable | Optional 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
| Marker | Purpose |
+kubebuilder:subresource:status | Enable status subresource |
+kubebuilder:subresource:scale | Enable scale subresource |
+kubebuilder:validation:Minimum=1 | Minimum value |
+kubebuilder:validation:Maximum=100 | Maximum value |
+kubebuilder:default=1 | Default value |
+kubebuilder:printcolumn | Additional printer columns |
+kubebuilder:webhook | Generate webhook config |
Operator SDK vs Kubebuilder
| Aspect | Operator SDK | Kubebuilder |
| Maintainer | Red Hat | Kubernetes SIG |
| Core | controller-runtime | controller-runtime |
| CLI | operator-sdk | kubebuilder |
| Scaffolding | More options | Simpler |
| OLM | Built-in | Add-on |
| Best For | Enterprise, OLM | General 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
| Setting | Meaning |
| served: true | API accepts this version |
| storage: true | Primary 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
| Practice | Why |
| Start with v1alpha1 | Signal instability |
| Graduate to v1 | Stable API |
| Never change v1 schema | Compatibility |
| Use conversion webhooks | Multi-version support |
| Test conversion paths | Prevent 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:
- User deletes object
- Object is marked
deletionTimestamp - Controller sees finalizer, performs cleanup
- Controller removes finalizer
- 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 Apply | Server-Side Apply |
| Uses last-applied annotation | Uses managedFields |
| Whole-resource conflicts | Field-level conflicts |
| Hard with multiple controllers | Natural 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
| Benefit | Why |
| Field ownership | Know which controller owns which field |
| Conflict detection | Detect when another controller modifies your fields |
| Multi-controller | Multiple controllers can manage the same resource |
| Idempotent | Apply is naturally idempotent |
10. Operator Lifecycle Manager (OLM)
OLM manages the lifecycle of operators in a cluster.
OLM Components
| Component | Purpose |
| OLM Operator | Manages CSV lifecycle |
| Catalog Operator | Resolves dependencies |
| CatalogSource | Source of operator bundles |
| Subscription | Request to install an operator |
| ClusterServiceVersion (CSV) | Operator metadata |
| InstallPlan | Step-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
| Benefit | Why |
| Dependency resolution | Automatically installs CRDs |
| Upgrades | Safe operator upgrades |
| Multi-tenancy | Operator scoping |
| Catalog | Discoverable 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
| Level | Tool | Purpose |
| Unit | Go testing | Individual functions |
| Integration | envtest | Controller against real API server |
| E2E | KUTTL | Full cluster scenarios |
| Fuzzing | Go fuzzing | CRD 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
| CRD | Purpose |
| Prometheus | Prometheus instance |
| Alertmanager | Alertmanager instance |
| ServiceMonitor | Scrape configuration |
| PodMonitor | Pod scrape configuration |
| PrometheusRule | Alerting rules |
cert-manager
| CRD | Purpose |
| Certificate | TLS certificate request |
| Issuer | Namespace-scoped CA |
| ClusterIssuer | Cluster-scoped CA |
| CertificateRequest | Actual CSR |
Istio Operator
| CRD | Purpose |
| IstioOperator | Istio installation config |
| VirtualService | Traffic routing |
| DestinationRule | Load balancing |
| Gateway | Ingress/egress |
1:1 copy of the class Google Doc, code in code blocks.