Custom Resource Definitions (CRDs) extend Kubernetes API with custom object types. Operators are controllers that manage these custom resources using domain-specific logic.
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 |
┌─────────────────────────────────────────────────────────┐
│ 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:
// 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
}
Prerequisites:
Development Tools:
kubebuilder (v3.12+) - scaffolding and code generationoperator-sdk (optional) - alternative frameworkcontroller-gen - generates CRDs, RBACs, webhookskustomize - manages Kubernetes manifestsTesting Tools:
envtest - runs API server locally for unit testskind - Kubernetes in Docker for integration testsginkgo - BDD testing framework (optional)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:
make manifestsctrl.Result{RequeueAfter: time.Minute}When to Use Operators:
📚 Complete Examples: See REFERENCE.md for full controller implementations, webhook code, test suites, and production-ready patterns.
CRDs extend Kubernetes API with custom object types validated by OpenAPI v3 schemas.
Key Components:
+kubebuilder:validation:Minimum=1Essential 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:
+kubebuilder:subresource:status - Separate status endpoint+kubebuilder:subresource:scale - Enable kubectl scaleGenerate CRDs: make manifests → outputs to config/crd/bases/
See REFERENCE.md for complete CRD definition, versioning, and conversion webhooks.
Reconciliation Loop:
Ready, Progressing, Degraded)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:
controllerutil.CreateOrUpdate() - Idempotent create/updatecontrollerutil.SetControllerReference() - Automatic garbage collectioncontrollerutil.AddFinalizer() - Cleanup before deletionError Handling:
ctrl.Result{RequeueAfter: 30s}See REFERENCE.md for complete controller implementation with finalizers, owner references, and error handling.
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:
webhook.Validator or webhook.Defaulter interface// +kubebuilder:webhook:path=/validate-...,mutating=false,...make manifests generates webhook configRequirements:
failurePolicy: fail (default) - reject on webhook errorsSee REFERENCE.md for complete webhook examples, cert-manager setup, and validation patterns.
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:
Lease resource for coordinationDeployment:
spec:
replicas: 3 # High availability
containers:
- args:
- --leader-elect
See REFERENCE.md for RBAC requirements and lease configuration tuning.
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.
✅ Best Practices:
CreateOrUpdate - Simplifies create/update logicReady, Progressing, Degraded with detailed messages❌ Anti-Patterns:
/healthz and /readyz endpointsRequeue 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.
State Machine Operators
Model complex workflows as finite state machines
Use status phases to track progression through states
Implement state transition validations and guards
Multi-Tenancy Operators
Namespace isolation strategies
Shared vs dedicated operator deployments
RBAC scoping for tenant-specific resources
GitOps Integration
Reconcile against Git repository state
Implement drift detection and auto-remediation
Use annotations to track source commits
External Secret Management
Integrate with Vault, AWS Secrets Manager, or Azure Key Vault
Implement secret rotation without downtime
Use external-secrets operator pattern
Architecture Patterns:
Hub-Spoke Model - Central operator manages multiple clusters
Federated Model - Operators in each cluster coordinate via shared state
Active-Active - Operators in multiple clusters handle same resources
Implementation Considerations:
Use cluster-api for cluster lifecycle management
Implement cross-cluster service discovery (e.g., Submariner)
Handle network partitions and split-brain scenarios
Use consensus protocols for distributed state
Tools:
KubeFed (deprecated) - Kubernetes Federation v2
OCM (Open Cluster Management) - CNCF sandbox project
Argo CD ApplicationSet - Multi-cluster GitOps
Crossplane - Universal control plane for multi-cloud
What is OLM?
Package manager for Kubernetes operators
Handles installation, upgrades, and dependency management
Used by OpenShift and available as CNCF project
OLM Components:
Catalog - Repository of operator metadata (CSV, CRD)
Subscription - Declarative operator installation
InstallPlan - Execution plan for operator installation
ClusterServiceVersion (CSV) - Operator metadata and deployment info
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:
Define proper upgrade paths in CSV
Test upgrade scenarios (skip versions, downgrades)
Use semantic versioning
Document breaking changes in release notes
Property-Based Testing:
Use tools like gopter for property-based tests
Test invariants across state transitions
Generate random valid/invalid inputs
Chaos Testing:
Use Chaos Mesh or Litmus to inject failures
Test operator resilience to node failures, network partitions
Verify recovery from partial updates
Performance Testing:
Benchmark reconciliation loop latency
Test with 1000+ custom resources
Measure memory/CPU usage under load
Use profiling tools (pprof) for bottleneck analysis
Observability:
[ ] Metrics exported via Prometheus endpoint
[ ] Structured logging with levels (info, warn, error)
[ ] Distributed tracing (OpenTelemetry)
[ ] Custom metrics for business logic (e.g., backup success rate)
Security:
[ ] RBAC follows least-privilege principle
[ ] Secrets encrypted at rest and in transit
[ ] Pod Security Standards enforced
[ ] Network policies restrict traffic
[ ] Image vulnerability scanning in CI/CD
Reliability:
[ ] Leader election enabled for HA
[ ] Graceful shutdown with finalizers
[ ] Rate limiting to prevent API server overload
[ ] Circuit breakers for external dependencies
[ ] Backup/restore procedures documented
Operational:
[ ] Runbooks for common failure scenarios
[ ] SLO/SLI definitions (e.g., 99.9% reconciliation success)
[ ] Alerting rules for critical conditions
[ ] Upgrade/rollback procedures tested
[ ] Capacity planning documented
Official Documentation:
Bundled Resources in This Directory:
templates/crd-definition.yaml - Complete CRD with OpenAPI schema
templates/operator-scaffold.go - Controller with reconcile logic
templates/webhook.go - Validating and mutating webhooks
templates/rbac.yaml - RBAC manifests for operator deployment
scripts/setup-operator-dev.sh - Development environment setup
resources/operator-patterns.md - Common patterns and anti-patterns
Community Resources:
Example Production Operators:
Build a Simple Operator - Start with a basic CRD and controller
Add Validation - Implement admission webhooks
Test Thoroughly - Write unit tests with envtest, integration tests with kind
Observe in Production - Deploy with metrics, logging, and tracing
Iterate - Add features based on operational experience
Advanced Topics to Explore:
Custom admission plugins
API aggregation and extension API servers
Operator Hub and OLM
Multi-cluster federation
Operator performance optimization
npx skills add williamzujkowski/advanced-kubernetes下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Category:other
Tags:operators, crd, kubebuilder, controllers, webhooks