/kubernetes-platform-skills:kubernetes-operator-developmentfrom kubernetes-platform-skills
Guides building Kubernetes Operators with Kubebuilder or Operator SDK — CRD API design, controller scaffolding, reconciliation loops, finalizers, and envtest testing.
Ships in kubernetes-platform-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
An Operator encodes operational knowledge — how to provision, upgrade, back up, and heal an application — as a Kubernetes controller watching a custom resource, so operating that application becomes "apply a YAML spec" instead of a runbook. Building one wrong (a reconcile loop that isn't idempotent, a CRD with no versioning strategy, a controller that never terminates finalizers) produces a system that appears to work in demos and then deadlocks, leaks resources, or corrupts state under real concurrent load. This skill covers designing the CRD API and writing a reconciliation loop that is safe to run continuously against a live cluster.
spec/status schema, including which fields
are user-desired-state vs. controller-observed-state.Reconcile() function for correctness
(idempotency, requeue behavior, error handling).envtest/kind instead of only manual
cluster testing.controller-runtime (the version of controller-runtime pulled in
determines available features like server-side apply support and
workqueue rate limiting defaults — check go.mod after scaffolding).kubectl and a disposable cluster (kind or minikube) for manual
verification; envtest (bundled via setup-envtest) for running
reconcile tests against a real API server + etcd without a full
kubelet/scheduler, in CI.Confirm an Operator is the right tool. If the task is "run this once" (a migration, a one-time provisioning step), a Job or a CI pipeline step is simpler and has no ongoing failure mode to maintain. Build an Operator when there's genuine ongoing reconciliation work: the desired state can drift from actual state over time and needs continuous correction (e.g. managing a clustered database's topology, rotating credentials, scaling based on custom metrics).
Scaffold the project and API:
kubebuilder init --domain example.com --repo github.com/example/cache-operator
kubebuilder create api --group cache --version v1alpha1 --kind RedisCluster --resource --controller
Design the CRD spec/status split explicitly — spec is
user-declared desired state; status is controller-observed actual
state, and only the controller should ever write to status:
type RedisClusterSpec struct {
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=15
Replicas int32 `json:"replicas"`
// +kubebuilder:validation:Enum=Standard;HighMemory
// +kubebuilder:default=Standard
Tier string `json:"tier,omitempty"`
}
type RedisClusterStatus struct {
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
Phase string `json:"phase,omitempty"`
Conditions []metav1.Condition `json:"conditions,omitempty"`
}
Start the API at v1alpha1 — it signals "no compatibility guarantee
yet" and gives room to fix schema mistakes before committing to
v1beta1/v1 conversion webhooks.
Write the reconcile loop as idempotent and level-triggered, never assuming it runs exactly once per change:
func (r *RedisClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var rc cachev1alpha1.RedisCluster
if err := r.Get(ctx, req.NamespacedName, &rc); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if !rc.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, &rc)
}
if !controllerutil.ContainsFinalizer(&rc, redisFinalizer) {
controllerutil.AddFinalizer(&rc, redisFinalizer)
if err := r.Update(ctx, &rc); err != nil {
return ctrl.Result{}, err
}
}
desired := buildStatefulSet(&rc)
var current appsv1.StatefulSet
err := r.Get(ctx, client.ObjectKeyFromObject(desired), ¤t)
switch {
case apierrors.IsNotFound(err):
if err := ctrl.SetControllerReference(&rc, desired, r.Scheme); err != nil {
return ctrl.Result{}, err
}
if err := r.Create(ctx, desired); err != nil {
return ctrl.Result{}, err
}
case err != nil:
return ctrl.Result{}, err
default:
if !equalSpec(current.Spec, desired.Spec) {
current.Spec = desired.Spec
if err := r.Update(ctx, ¤t); err != nil {
return ctrl.Result{}, err
}
}
}
rc.Status.ObservedGeneration = rc.Generation
rc.Status.Phase = derivePhase(current)
if err := r.Status().Update(ctx, &rc); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
}
Every branch either returns an error (triggering exponential-backoff requeue from the workqueue) or a deterministic result — never a silent no-op that leaves drift uncorrected.
Use finalizers for any resource with external side effects that must be cleaned up before Kubernetes garbage-collects the object (external cloud resources, DNS records, other clusters' state):
const redisFinalizer = "cache.example.com/cleanup"
func (r *RedisClusterReconciler) reconcileDelete(ctx context.Context, rc *cachev1alpha1.RedisCluster) (ctrl.Result, error) {
if err := deprovisionExternalBackupBucket(ctx, rc); err != nil {
return ctrl.Result{}, err // finalizer stays, delete is retried
}
controllerutil.RemoveFinalizer(rc, redisFinalizer)
return ctrl.Result{}, r.Update(ctx, rc)
}
Warning: if a finalizer's cleanup logic can never succeed (a bug, a permanently unreachable external system, or the finalizer string itself was mistyped/orphaned), the custom resource — and anything Kubernetes-garbage-collection-blocked behind it — becomes stuck in
Terminatingforever. Recovering requires manually patching out the finalizer (kubectl patch ... -p '{"metadata":{"finalizers":[]}}' --type=merge), which skips the cleanup the finalizer existed to guarantee — treat this as an incident, not a routine unstick command, and confirm the external resource really doesn't need manual cleanup first.
Report status via status.conditions, not just a free-text phase
string, so other tooling (dashboards, kubectl wait --for=condition=)
can consume it reliably:
meta.SetStatusCondition(&rc.Status.Conditions, metav1.Condition{
Type: "Ready",
Status: metav1.ConditionTrue,
Reason: "AllReplicasAvailable",
Message: "3/3 replicas ready",
ObservedGeneration: rc.Generation,
})
Test with envtest before relying on manual kind testing for
every change:
var _ = Describe("RedisCluster controller", func() {
It("creates a StatefulSet matching spec.replicas", func() {
rc := &cachev1alpha1.RedisCluster{ /* ... */ Spec: cachev1alpha1.RedisClusterSpec{Replicas: 3} }
Expect(k8sClient.Create(ctx, rc)).To(Succeed())
Eventually(func() int32 {
var sts appsv1.StatefulSet
_ = k8sClient.Get(ctx, client.ObjectKeyFromObject(rc), &sts)
return *sts.Spec.Replicas
}).Should(Equal(int32(3)))
})
})
make test # runs envtest-backed suite via ginkgo
Install the CRD and run the controller against a kind cluster
before shipping:
make install # kubectl apply -f config/crd
make run # runs the controller locally against the cluster's API server
Package for distribution. For a plain chart-based install, wrap
config/crd + config/rbac + config/manager into a Helm chart
(see helm-chart-authoring,
putting CRDs under the chart's crds/ directory since Helm never
upgrades or deletes files there automatically). For OLM-based
distribution (OpenShift), use operator-sdk generate bundle to
produce a ClusterServiceVersion and bundle image.
Reconcile fully re-entrant and safe to call with stale or
duplicate events — controller-runtime's workqueue coalesces and
retries events, so "reconcile ran twice for one change" is normal, not
a bug to work around with external locking.ObservedGeneration vs. .metadata.generation before
reporting a condition as current, so a status update from a stale
reconcile of an already-superseded spec doesn't overwrite a newer
status.SetControllerReference/owner references on every child resource
the controller creates, so Kubernetes garbage-collects children
automatically when the parent custom resource is deleted (except
where a finalizer intentionally intercepts deletion first for external
cleanup).controller-runtime
does this by default with exponential backoff) rather than hot-looping
reconciliation against a failing dependency.v1alpha1
onward even if you don't need a webhook yet — plan which fields could
need renaming, and prefer additive changes to avoid a conversion
webhook becoming mandatory later.config/rbac to exactly the resources/verbs the
controller touches (kubebuilder:rbac markers) instead of granting
the controller's ServiceAccount cluster-admin "to be safe" — an
over-privileged controller is a top attack-surface risk in clusters
running third-party Operators.Symptom: The controller works in testing but under real load
starts making conflicting writes / 409 Conflict errors on Update.
Fix: Missing optimistic-concurrency handling. Re-Get the object
and retry on conflict (client.IgnoreNotFound + a retry helper like
retry.RetryOnConflict) rather than treating every Update as
guaranteed to succeed against the resource version last read.
Symptom: Deleting the custom resource hangs indefinitely; kubectl get shows it stuck with a deletionTimestamp set but the object
never disappears.
Fix: A finalizer's cleanup path is erroring out (check controller
logs) or was left on the object by a previous controller version that
no longer exists to remove it. Fix the underlying cleanup failure
first; only manually patch the finalizer list as a last resort, and
only after confirming external resources don't need the cleanup that
finalizer guaranteed.
Symptom: Deleting the CRD itself (kubectl delete crd redisclusters.cache.example.com) cascades to delete every
RedisCluster custom resource across every namespace, and their owned
StatefulSets/PVCs along with them.
Fix: This is expected Kubernetes behavior — deleting a CRD deletes
all its instances. > Warning: never delete a CRD as a
troubleshooting step on a production cluster; it is equivalent to
deleting every resource of that kind cluster-wide. Confirm no
instances exist (kubectl get <kind> -A) or explicitly accept the
data-loss blast radius before proceeding.
Symptom: Two reconciler replicas (run for HA) both act on the same
resource simultaneously, causing duplicate child-resource creation.
Fix: Controller-runtime managers use leader election
(--leader-elect=true) to ensure only one replica reconciles at a
time; confirm it's enabled in the manager setup and that the
Lease-based leader election RBAC/permissions are actually granted —
a manager silently failing to acquire the lease due to missing RBAC
can otherwise leave no active reconciler rather than duplicating
work, which looks like the controller "randomly stopped working."
Symptom: A schema change to the CRD (renaming a spec field) breaks every existing custom resource instance in the cluster after upgrade. Fix: CRD schema changes are not automatically migrated. Add a new field alongside the old one, dual-read in the controller for one release, and only remove the old field after all instances have been migrated (a conversion webhook is the safe path for a true rename across API versions instead of an in-place field rename).
Scenario: A RedisCluster CRD that reconciles a StatefulSet and
reports readiness via conditions, packaged for kind testing.
# config/samples/cache_v1alpha1_rediscluster.yaml
apiVersion: cache.example.com/v1alpha1
kind: RedisCluster
metadata:
name: sessions-cache
spec:
replicas: 3
tier: Standard
make manifests generate # regenerate CRD YAML + deepcopy funcs from markers
kind create cluster --name operator-dev
make install # apply CRDs
make run & # run the controller against kind, out-of-cluster
kubectl apply -f config/samples/cache_v1alpha1_rediscluster.yaml
kubectl get rediscluster sessions-cache -o jsonpath='{.status.conditions}'
Expected status after reconciliation stabilizes:
[{"type":"Ready","status":"True","reason":"AllReplicasAvailable","message":"3/3 replicas ready","observedGeneration":1}]
kubectl get statefulset sessions-cache shows 3/3 ready replicas, and
kubectl get statefulset sessions-cache -o jsonpath='{.metadata.ownerReferences}'
confirms the StatefulSet is owned by the RedisCluster, so deleting the
custom resource (once its finalizer's external-cleanup step succeeds)
garbage-collects the StatefulSet and its Pods automatically — though not
its PVCs by default, which is worth calling out explicitly to whoever
deletes a RedisCluster expecting full cleanup.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
kubernetes-operators, kubebuilder, operator-sdk, crd, controller-runtime, olm
npx claudepluginhub selvarajmurugesan90/ops-engineering-skills --plugin kubernetes-platform-skills35 skills in this plugin
/cert-manager-tls-automationGuides installing and configuring cert-manager for automated TLS certificate issuance and renewal — Issuers vs. ClusterIssuers, ACME/ Let's Encrypt HTTP-01 and DNS-01 challenges, private-CA issuance, and integration with Ingress-nginx and Istio gateways. Use when a user asks to "automate TLS certificates on Kubernetes," "set up cert-manager with Let's Encrypt," "fix a stuck Certificate that won't become Ready," "use DNS-01 for a wildcard cert," "rotate mTLS certs automatically," or "issue certs from an internal CA."
/cni-networking-calico-flannelGuides choosing and installing a Kubernetes CNI plugin — Calico vs. Flannel — including NetworkPolicy enforcement capability differences, BGP vs. VXLAN/overlay data paths, and IP address management (IPAM) tradeoffs. Use when a user asks to "choose a CNI plugin for Kubernetes," "enable NetworkPolicy enforcement," "set up Calico with BGP peering," "install Flannel," "debug pod-to-pod connectivity across nodes," or "migrate from Flannel to Calico."
/complete-kubernetes-deployment-on-aks-from-scratchSequences a complete, end-to-end AKS deployment from a bare Azure subscription to a production-ready cluster serving a first workload — Azure landing zone prerequisites, AKS cluster and node pool provisioning, Azure CNI (with the Calico/Cilium alternative noted), ingress (Application Gateway Ingress Controller vs. ingress-nginx), cert-manager with Azure DNS, conformance validation, a Helm-deployed workload, and a node/cluster health baseline. This is an integration/orchestration skill that sequences several existing tool-specific skills in the correct order and flags the handoff points between them — it does not restate their internals. Use when a user asks to "deploy a Kubernetes cluster on AKS from scratch," "set up a new AKS environment end to end," "build a production AKS cluster from a fresh Azure subscription," or "give me the full sequence to go from nothing to a working AKS cluster."
/complete-kubernetes-deployment-on-eks-from-scratchSequences a complete, end-to-end EKS deployment from a bare AWS account to a production-ready cluster serving a first workload — landing zone/IAM prerequisites, EKS cluster and node group provisioning, VPC CNI (with the Calico/Cilium alternative noted), ingress (ALB vs. ingress-nginx), cert- manager with Route 53 DNS-01, conformance validation, a Helm-deployed workload, and a node/cluster health baseline. This is an integration/ orchestration skill that sequences several existing tool-specific skills in the correct order and flags the handoff points between them — it does not restate their internals. Use when a user asks to "deploy a Kubernetes cluster on EKS from scratch," "stand up a new EKS environment end to end," "build a production EKS cluster from a fresh AWS account," or "give me the full sequence to go from nothing to a working EKS cluster."
/complete-kubernetes-deployment-on-gke-from-scratchSequences a complete, end-to-end GKE deployment from a bare GCP project to a production-ready cluster serving a first workload — GCP landing zone prerequisites, GKE cluster and node pool provisioning, VPC-native/ Dataplane V2 CNI (with the Calico alternative noted), ingress (GKE Ingress/Gateway API vs. ingress-nginx), cert-manager with Cloud DNS, conformance validation, a Helm-deployed workload, and a node/cluster health baseline. This is an integration/orchestration skill that sequences several existing tool-specific skills in the correct order and flags the handoff points between them — it does not restate their internals. Use when a user asks to "deploy a Kubernetes cluster on GKE from scratch," "set up a new GKE environment end to end," "build a production GKE cluster from a fresh GCP project," or "give me the full sequence to go from nothing to a working GKE cluster."
/complete-kubernetes-deployment-on-oke-oci-from-scratchSequences a complete, end-to-end OKE (Oracle Container Engine for Kubernetes) deployment from a bare OCI tenancy to a production-ready cluster serving a first workload — OCI landing zone prerequisites (Compartments, Dynamic Groups), OKE Enhanced cluster and node pool provisioning, VCN-Native pod networking (with the Calico NetworkPolicy add-on noted), ingress (Native Ingress Controller vs. ingress-nginx), cert-manager with OCI DNS via a community webhook solver, conformance validation, a Helm-deployed workload, and a node/cluster health baseline. This is an integration/orchestration skill sequencing several existing tool-specific skills in the correct order and flagging the handoff points between them — it does not restate their internals. Use when a user asks to "deploy a Kubernetes cluster on OKE from scratch," "set up OKE on OCI end to end," "build a production OKE cluster from a fresh OCI tenancy," or "give me the full sequence to go from nothing to a working OKE cluster."
Other plugins' skills for the same job