Advanced kubernetes

From williamzujkowski/standards · View interactive version

Advanced kubernetes is an AI agent skill from the GitHub repository williamzujkowski/standards. Custom Resource Definitions (CRDs) extend Kubernetes API with custom object types. Operators are controllers that manage these custom resources using domain-specific logic.

How to use this skill

Skill file

Advanced Kubernetes: Operators & CRDs

Level 1: Quick Reference

Core Concepts at a Glance

Custom Resource Definitions (CRDs) extend Kubernetes API with custom object types. Operators are controllers that manage these custom resources using domain-specific logic.

CRD vs ConfigMap Comparison:

| Aspect | CRD | ConfigMap |

|--------|-----|-----------|

| API Integration | Full Kubernetes API support (CRUD, watch, RBAC) | Simple key-value storage |

| Validation | OpenAPI v3 schema validation, admission webhooks | No built-in validation |

| Versioning | Multiple versions with conversion webhooks | Single version only |

| Use Case | Complex application state, declarative APIs | Configuration data, environment variables |

| Controller Support | Reconciliation loops, status tracking | Manual polling required |

| Example | Database instances, ML workflows, backup policies | App config files, feature flags |

Operator Pattern Overview

┌─────────────────────────────────────────────────────────┐
│                    Kubernetes API Server                 │
│  (stores desired state in etcd)                         │
└────────────┬────────────────────────────┬───────────────┘
             │                            │
             │ Watch                      │ Update Status
             ↓                            ↑
    ┌────────────────┐         ┌─────────────────────┐
    │   Controller   │────────→│  External Resources │
    │  (Reconcile)   │  Manage │  (DBs, APIs, etc.)  │
    └────────────────┘         └─────────────────────┘
         ↑
         │ Compare
         │
    ┌────┴─────┐
    │ Desired  │
    │ vs Actual│
    └──────────┘

Reconciliation Loop:

  1. Watch - Controller watches for changes to custom resources
  2. Compare - Reconcile function compares desired vs actual state
  3. Act - Controller takes actions to align actual state with desired
  4. Update Status - Controller updates resource status with current state
  5. Requeue - Schedule next reconciliation (periodic or event-driven)

Controller Reconciliation Logic

// Simplified reconciliation pattern
func (r *MyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    // 1. Fetch the custom resource
    obj := &myapi.MyResource{}
    if err := r.Get(ctx, req.NamespacedName, obj); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // 2. Handle deletion (finalizers)
    if !obj.DeletionTimestamp.IsZero() {
        return r.handleDeletion(ctx, obj)
    }

    // 3. Reconcile external state
    if err := r.reconcileExternal(ctx, obj); err != nil {
        return ctrl.Result{}, err
    }

    // 4. Update status
    obj.Status.Ready = true
    if err := r.Status().Update(ctx, obj); err != nil {
        return ctrl.Result{}, err
    }

    return ctrl.Result{}, nil // Success, no requeue
}

Essential Checklist

Prerequisites:

Development Tools:

Testing Tools:

Key Files in Operator Project:

my-operator/
├── api/v1/           # CRD definitions (Go structs)
├── config/
│   ├── crd/          # Generated CRD YAML
│   ├── rbac/         # Generated RBAC YAML
│   ├── manager/      # Operator deployment
│   └── webhook/      # Webhook configurations
├── controllers/      # Reconciliation logic
├── main.go           # Entrypoint (manager setup)
└── Dockerfile        # Container image build

Quick Commands:

# Initialize operator project
kubebuilder init --domain example.com --repo github.com/myorg/my-operator

# Create CRD + controller
kubebuilder create api --group apps --version v1 --kind MyApp

# Generate manifests
make manifests

# Run locally (connects to current kubeconfig cluster)
make install run

# Run tests
make test

# Build and deploy
make docker-build docker-push deploy IMG=myregistry/my-operator:v1.0.0

Common Pitfalls:

When to Use Operators:


Level 2: Implementation Guide

📚 Complete Examples: See REFERENCE.md for full controller implementations, webhook code, test suites, and production-ready patterns.

2.1 Custom Resource Definitions (CRDs)

CRDs extend Kubernetes API with custom object types validated by OpenAPI v3 schemas.

Key Components:

Essential Kubebuilder Markers:

// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=10
Size int32 `json:"size"`

// +kubebuilder:validation:Pattern=`^[a-z0-9.-]+/[a-z0-9.-]+:[a-z0-9.-]+$`
Image string `json:"image"`

// +optional
Port int32 `json:"port,omitempty"`

Printcolumns for kubectl get:

// +kubebuilder:printcolumn:name="Ready",type=integer,JSONPath=`.status.readyReplicas`
// +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`

Subresources:

Generate CRDs: make manifests → outputs to config/crd/bases/

See REFERENCE.md for complete CRD definition, versioning, and conversion webhooks.


2.2 Operators and Controllers

Reconciliation Loop:

  1. Watch - Controller watches for resource changes (via informers/caches)
  2. Compare - Reconcile compares desired vs actual state
  3. Act - Create/update/delete Kubernetes resources to match desired state
  4. Update Status - Set status conditions (Ready, Progressing, Degraded)
  5. Requeue - Schedule next reconciliation (event-driven or periodic)

Controller Pattern:

func (r *Reconciler) Reconcile(ctx, req) (ctrl.Result, error) {
    // 1. Fetch custom resource
    obj := &MyResource{}
    if err := r.Get(ctx, req.NamespacedName, obj); err != nil {
        return ctrl.Result{}, client.IgnoreNotFound(err)
    }

    // 2. Handle deletion (finalizers)
    if !obj.DeletionTimestamp.IsZero() {
        return r.handleDeletion(ctx, obj)
    }

    // 3. Reconcile external state
    if err := r.reconcileDeployment(ctx, obj); err != nil {
        return ctrl.Result{RequeueAfter: 30*time.Second}, err
    }

    // 4. Update status
    obj.Status.Ready = true
    return ctrl.Result{}, r.Status().Update(ctx, obj)
}

Key Functions:

Error Handling:

See REFERENCE.md for complete controller implementation with finalizers, owner references, and error handling.


2.3 Admission Webhooks

Webhooks intercept API requests before persistence for validation/mutation.

Types:

Implementation:

// Validating webhook
func (r *MyApp) ValidateCreate() (admission.Warnings, error) {
    if r.Spec.Size < 1 || r.Spec.Size > 100 {
        return nil, fmt.Errorf("size must be 1-100")
    }
    return nil, nil
}

// Mutating webhook (Defaulter)
func (r *MyApp) Default() {
    if r.Spec.Port == 0 {
        r.Spec.Port = 8080
    }
}

Setup:

  1. Implement webhook.Validator or webhook.Defaulter interface
  2. Add kubebuilder marker: // +kubebuilder:webhook:path=/validate-...,mutating=false,...
  3. make manifests generates webhook config
  4. Deploy with cert-manager for TLS certificates

Requirements:

See REFERENCE.md for complete webhook examples, cert-manager setup, and validation patterns.


2.4 Leader Election & High Availability

Leader election ensures only one controller instance reconciles at a time (prevents race conditions).

Configuration:

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
    LeaderElection:          true,
    LeaderElectionID:        "myapp-controller.example.com",
    LeaderElectionNamespace: "myapp-system",
})

How It Works:

Deployment:

spec:
  replicas: 3  # High availability
  containers:
  - args:
    - --leader-elect

See REFERENCE.md for RBAC requirements and lease configuration tuning.


2.5 Testing Operators

Unit Testing with envtest:

Setup:

testEnv = &envtest.Environment{
    CRDDirectoryPaths: []string{filepath.Join("..", "config", "crd", "bases")},
}
cfg, _ := testEnv.Start()
k8sClient, _ = client.New(cfg, client.Options{Scheme: scheme.Scheme})

Test Pattern:

It("Should create Deployment", func() {
    myApp := &MyApp{...}
    Expect(k8sClient.Create(ctx, myApp)).Should(Succeed())

    deployment := &Deployment{}
    Eventually(func() error {
        return k8sClient.Get(ctx, namespacedName, deployment)
    }, timeout, interval).Should(Succeed())

    Expect(*deployment.Spec.Replicas).To(Equal(int32(3)))
})

Integration Testing with kind:

kind create cluster
make docker-build docker-push deploy IMG=operator:test
kubectl wait --for=condition=available deployment/operator
kubectl apply -f test-cr.yaml

See REFERENCE.md for complete test suites, ginkgo patterns, and E2E test scripts.


2.6 Best Practices & Anti-Patterns

✅ Best Practices:

❌ Anti-Patterns:

Requeue Strategies:

// Immediate requeue (rate-limited)
return ctrl.Result{Requeue: true}, nil

// Requeue after delay
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil

// No requeue (wait for watch event)
return ctrl.Result{}, nil

// Error (exponential backoff)
return ctrl.Result{}, fmt.Errorf("transient error")

See REFERENCE.md for advanced patterns, multi-cluster operators, and OLM integration.


Level 3: Deep Dive Resources

Advanced Operator Patterns

State Machine Operators

Multi-Tenancy Operators

GitOps Integration

External Secret Management

Multi-Cluster Operators

Architecture Patterns:

  1. Hub-Spoke Model - Central operator manages multiple clusters
  1. Federated Model - Operators in each cluster coordinate via shared state
  1. Active-Active - Operators in multiple clusters handle same resources

Implementation Considerations:

Tools:

Operator Lifecycle Manager (OLM)

What is OLM?

OLM Components:

Creating an OLM Bundle:


# Generate bundle manifests

operator-sdk generate bundle --version 1.0.0



# Validate bundle

operator-sdk bundle validate ./bundle



# Build and push bundle image

docker build -f bundle.Dockerfile -t myregistry/myapp-operator-bundle:v1.0.0 .

docker push myregistry/myapp-operator-bundle:v1.0.0



# Add to catalog

opm index add --bundles myregistry/myapp-operator-bundle:v1.0.0 \

  --tag myregistry/myapp-catalog:latest

OLM Best Practices:

Advanced Testing Strategies

Property-Based Testing:

Chaos Testing:

Performance Testing:

Production Readiness Checklist

Observability:

Security:

Reliability:

Operational:

Resources and Further Learning

Official Documentation:

Bundled Resources in This Directory:

  1. templates/crd-definition.yaml - Complete CRD with OpenAPI schema
  1. templates/operator-scaffold.go - Controller with reconcile logic
  1. templates/webhook.go - Validating and mutating webhooks
  1. templates/rbac.yaml - RBAC manifests for operator deployment
  1. scripts/setup-operator-dev.sh - Development environment setup
  1. resources/operator-patterns.md - Common patterns and anti-patterns

Community Resources:

Example Production Operators:

Next Steps

  1. Build a Simple Operator - Start with a basic CRD and controller
  1. Add Validation - Implement admission webhooks
  1. Test Thoroughly - Write unit tests with envtest, integration tests with kind
  1. Observe in Production - Deploy with metrics, logging, and tracing
  1. Iterate - Add features based on operational experience

Advanced Topics to Explore:

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.