The API and the loopLesson 8 of 8
- Desired state and the reconcile loop, not reconciled
- Control plane and nodes, not reconciled
- API machinery: groups, versions and resource versions, not reconciled
- kubectl and kubeconfig, not reconciled
- Namespaces, labels and annotations, not reconciled
- Declarative management and server-side apply, not reconciled
- Owners, finalizers and garbage collection, not reconciled
- Custom resources and operators, not reconciled
Custom resources and operators
A CustomResourceDefinition adds a resource type to the API with schema validation, status and versions. An operator is the controller that gives that type behaviour, reconciling each object toward what its spec asks for.
Shows the lesson one block at a time. Arrow keys step, number keys jump to a scene, and Escape returns to the page where you were.
Every built-in resource, from pods to NetworkPolicies, is compiled into the API server. A CustomResourceDefinition lets you add your own, and the API server serves it with the same machinery: REST paths, watch, RBAC, admission, kubectl. On its own a custom resource is only stored data. An operator is the controller that turns that data into action. Together they are how most of the ecosystem extends Kubernetes, from cert-manager’s Certificates to database operators to AWS resources exposed as objects.
This lesson builds one example throughout: a Backup resource in the group ops.example.com that asks for a scheduled database backup, and an operator that makes the backups happen.
Reconcile, in 7 scenes
CRDs extend the API
A CustomResourceDefinitionA cluster-scoped object that registers a resource type with the API server: its group, names, scope, versions and schema. (CRD) declares the type; each object of that type is a custom resourceAn object of a type defined by a CRD, stored by the API server like a built-in object and acted on by whatever controller watches it.. Before the CRD exists, the API knows nothing of the type:
kubectl api-resources --api-group=ops.example.com
NAME SHORTNAMES APIVERSION NAMESPACED KIND
kubectl get backups -n orders
error: the server doesn't have a resource type "backups"
kubectl apply -f backup.yaml
error: resource mapping not found for name: "orders-nightly" namespace: "orders" from "backup.yaml": no matches for kind "Backup" in version "ops.example.com/v1" ensure CRDs are installed first
Once you create the CRD and the API server marks it Established, the type appears in discovery and you can create, list, watch and delete Backups at /apis/ops.example.com/v1/namespaces/<namespace>/backups. The same RBAC rules apply, so a Role can grant get on backups in one namespace. The API server needs no code for any of this; it stores custom resources in etcd like everything else.
A few naming rules are fixed. The CRD’s metadata.name must be <plural>.<group>, here backups.ops.example.com. The group should be a DNS name you control, so that two vendors’ Backup types never collide. scope is Namespaced or Cluster, and names sets the kind, the plural used in URLs, the singular, and optional short names for kubectl.
Custom resources are served as JSON and YAML. They do not support Protocol Buffers, the binary encoding that built-in types support; aggregated API servers can. CBOR support for custom resources arrived as alpha in Kubernetes 1.32 behind the CBORServingAndStorage feature gate.
Schemas and validation
Each version carries an OpenAPI v3 schema. The full CRD for the example:
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: backups.ops.example.com
spec:
group: ops.example.com
scope: Namespaced
names:
plural: backups
singular: backup
kind: Backup
shortNames: [bk]
versions:
- name: v1
served: true
storage: true
subresources:
status: {}
additionalPrinterColumns:
- name: Database
type: string
jsonPath: .spec.database
- name: Schedule
type: string
jsonPath: .spec.schedule
- name: Phase
type: string
jsonPath: .status.phase
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [database, schedule, target]
properties:
database:
type: string
minLength: 1
maxLength: 63
x-kubernetes-validations:
- rule: self == oldSelf
message: database is immutable
schedule:
type: string
maxLength: 100
engineVersion:
type: string
pattern: '^\d+(\.\d+)?$'
retentionDays:
type: integer
minimum: 1
maximum: 365
default: 7
throttleMBps:
type: number
minimum: 0
suspend:
type: boolean
default: false
target:
type: object
required: [kind]
x-kubernetes-validations:
- rule: "self.kind != 'S3' || has(self.bucket)"
message: bucket is required when kind is S3
properties:
kind:
type: string
enum: [S3, PVC]
bucket:
type: string
maxLength: 63
claimName:
type: string
maxLength: 253
status:
type: object
properties:
phase:
type: string
enum: [Pending, Scheduled, Failed]
lastSuccessfulTime:
type: string
format: date-time
observedGeneration:
type: integer
format: int64
conditions:
type: array
x-kubernetes-list-type: map
x-kubernetes-list-map-keys: [type]
items:
type: object
required: [type, status]
properties:
type:
type: string
status:
type: string
reason:
type: string
message:
type: string
lastTransitionTime:
type: string
format: date-time
observedGeneration:
type: integer
format: int64
The schema must be a structural schemaA CRD schema in which every field declares a type and the shape of objects and arrays, so the API server knows the full structure of valid objects.. Every field states one of string, integer, number (a floating-point value, double in CEL), boolean, array or object. Two extensions cover the exceptions: x-kubernetes-int-or-string for fields such as ports that accept either, and x-kubernetes-preserve-unknown-fields for a subtree the schema deliberately leaves open.
A structural schema lets the API server do three things before it stores an object:
- Pruning. Fields the schema does not declare are dropped.
kubectlsends requests with--validate=strictby default, and server-side field validation, GA in Kubernetes 1.27, turns an unknown or duplicated field into a400error instead of silently dropping it. Controllers built on client-go default to warnings. - Defaulting.
default:values fill absent fields on create and update, and when an object is read from etcd. A Backup created withoutretentionDaysreads back with7. - Validation. OpenAPI keywords such as
minimum,maxLength,enumandpatterncheck single fields.
Rules that span fields, or that compare an update with what was stored, are written in CEL under x-kubernetes-validations, GA since Kubernetes 1.29. Each rule is evaluated with self bound to the field it sits on. The rule on target is a cross-field check: a bucket is required when the target kind is S3. The rule on database is a transition ruleA CEL validation rule that refers to oldSelf, the stored value. It runs only on updates, and expresses rules such as immutability or allowed state changes.: self == oldSelf makes the field immutable after creation. A rule can also set messageExpression to build the message from the values involved, reason to return a machine-readable failure reason such as FieldValueForbidden, and fieldPath to point the error at a nested field. The API server estimates the cost of every rule when the CRD is written and rejects any rule whose estimated cost exceeds the limit, which is why the strings and lists in the schema declare maxLength and similar limits.
Without ratcheting, a stricter rule added to a CRD with existing objects blocks every update to an object that violates it, even one that only changes a label. Validation ratcheting, GA in Kubernetes 1.33, allows an update when the fields that fail validation are unchanged from the stored object, so you can tighten a schema without blocking unrelated edits.
With CEL in the CRD itself, a validating webhook is needed only for checks that depend on something outside the object: another object, an external system, or a quota held elsewhere. A webhook is a service that must stay up, and with the default failure policy every write to its resources fails while it is down; a CEL rule runs inside the API server.
Subresources and columns
The status subresource splits an object into two endpoints. The main endpoint ignores changes to status, and /status ignores changes to everything else. Users who can edit a Backup’s spec cannot forge its status, and RBAC grants backups/status separately to the operator. The API server also increments metadata.generation only for changes outside metadata and status, so a controller can record the generation it last acted on in status.observedGeneration and anyone can tell whether the status is current.
The scale subresource makes a custom resource work with kubectl scale and the HorizontalPodAutoscaler. It maps three paths:
subresources:
status: {}
scale:
specReplicasPath: .spec.replicas
statusReplicasPath: .status.replicas
labelSelectorPath: .status.labelSelector
specReplicasPath must point under .spec and statusReplicasPath under .status; both are required, and the status path conventionally points at .status.replicas, the observed count. labelSelectorPath is required for the HorizontalPodAutoscaler and must point at a string field holding a serialized selector such as app.kubernetes.io/name=db, not a selector object.
additionalPrinterColumns sets what kubectl get prints. Without them you get only NAME and AGE. A column with priority: 1 appears only with -o wide. selectableFields, GA in Kubernetes 1.32, lets clients filter on declared fields with --field-selector, so kubectl get backups --field-selector spec.database=orders-db works once .spec.database is listed there.
Versions and conversion
A CRD can serve several versions of the same resource. Each entry in versions has its own schema and a served flag, and exactly one has storage: true: the version objects are written to etcd in. Objects can be read and written through any served version, and the API server converts between them.
versions:
- name: v1alpha1
served: true
storage: false
deprecated: true
deprecationWarning: ops.example.com/v1alpha1 Backup is deprecated; use ops.example.com/v1
- name: v1
served: true
storage: true
conversion:
strategy: Webhook
webhook:
conversionReviewVersions: [v1]
clientConfig:
service:
namespace: backup-system
name: backup-operator-webhook
path: /convert
Schemas omitted for brevity. With strategy: None, the default, conversion rewrites only apiVersion, which is correct only when the schemas are identical in shape. When a field is renamed or restructured between versions, a conversion webhook must translate in both directions without losing data, since a client may write v1alpha1 and read v1 back.
The storage versionThe one version of a CRD whose schema is used to write objects to etcd. Objects written earlier stay in the version they were written in until rewritten. changes only what is written from then on; existing objects stay in the old version until something rewrites them. The CRD’s status.storedVersions lists every version that may still be in etcd. Before you remove a version from versions, rewrite every stored object to the storage version and make sure status.storedVersions no longer lists the old one. Kubernetes 1.37 includes a built-in storage version migrator, GA and enabled by default. Create a StorageVersionMigration naming the group and resource, and a control plane controller rewrites every object in the storage version:
apiVersion: storagemigration.k8s.io/v1
kind: StorageVersionMigration
metadata:
name: backups-to-v1
spec:
resource:
group: ops.example.com
resource: backups
After a successful migration of a custom resource, the CRD’s status.storedVersions lists only the storage version. If it still lists the old one, the CRD changed while the migration ran, and the migration needs to run again before the old version can go.
The operator pattern
An operatorA controller, usually paired with one or more CRDs, that encodes the operational knowledge for running one application: installing it, upgrading it, backing it up, failing it over. applies the controller pattern from the start of this track to an application. The built-in controllers already behave this way. Delete a pod that a ReplicaSet owns and the ReplicaSet controller notices one fewer pod than it wants and creates another:
kubectl create deployment web --image=nginx:1.30 --replicas=3
deployment.apps/web created
kubectl get pods
NAME READY STATUS RESTARTS AGE web-757b6975cc-4qkml 1/1 Running 0 15s web-757b6975cc-6z4nz 1/1 Running 0 15s web-757b6975cc-c9b9k 1/1 Running 0 15s
kubectl delete pod web-757b6975cc-6z4nz --wait=false
pod "web-757b6975cc-6z4nz" deleted from default namespace
kubectl get pods
NAME READY STATUS RESTARTS AGE web-757b6975cc-4qkml 1/1 Running 0 16s web-757b6975cc-6z4nz 1/1 Terminating 0 16s web-757b6975cc-c9b9k 1/1 Running 0 16s web-757b6975cc-nng6d 1/1 Running 0 1s
kubectl get pods
NAME READY STATUS RESTARTS AGE web-757b6975cc-4qkml 1/1 Running 0 26s web-757b6975cc-c9b9k 1/1 Running 0 26s web-757b6975cc-nng6d 1/1 Running 0 11s
kubectl get events --field-selector involvedObject.kind=ReplicaSet
LAST SEEN TYPE REASON OBJECT MESSAGE 26s Normal SuccessfulCreate replicaset/web-757b6975cc Created pod: web-757b6975cc-6z4nz 26s Normal SuccessfulCreate replicaset/web-757b6975cc Created pod: web-757b6975cc-4qkml 26s Normal SuccessfulCreate replicaset/web-757b6975cc Created pod: web-757b6975cc-c9b9k 11s Normal SuccessfulCreate replicaset/web-757b6975cc Created pod: web-757b6975cc-nng6d
ExplainerThe reconcile loop
The Deployment goes at once; the garbage collector deletes its dependents after.
Each action runs as a kubectl command; it shows here.
Watch stream0 queued
- Nothing queued, nothing in flight.
and 0 more
Cache, by ownerReferences What the controllers have been told, not yet what is queued.
Empty: no Deployment, ReplicaSet or Pod named web.
No change delivered yet.
Delivered to the informers of
Every controller that watches the object's kind; the one that owns it acts.
- Observe
- What the controller that owns the object reads from its cache.
- Diff
- What the object asks for against what exists.
- Act
- The writes that close the gap, each queued as a change of its own.
Apply the Deployment. Its changes queue in the watch stream, and Step delivers them one at a time.
An operator does the same for its own types. The Backup operator watches Backups and the CronJobs it creates for them. When either changes, it reads the Backup, works out which CronJob should exist, creates or updates it, and writes the result into the Backup’s status. A database operator’s knowledge goes deeper: the order in which replicas are upgraded, how to promote a replica when the primary fails, when a backup is safe to take. That knowledge is what an operator adds over a set of manifests.
Controllers are level-based. A reconcile receives a namespace and name, never a description of what changed, and events for the same object are merged while it waits in the queue. It must therefore read the current state every time and do only what is still missing. That is what idempotent means here: running the reconcile again on an unchanged world changes nothing.
Writing a reconcile
Kubebuilder v4 scaffolds a Go operator on controller-runtime; Kubebuilder 4.16 targets Kubernetes 1.37 and controller-runtime v0.25. go/v4 is the default plugin.
kubebuilder init --domain example.com --repo example.com/backup-operator
kubebuilder create api --group ops --version v1 --kind Backup
make manifests
--repo sets the Go module path and is required outside GOPATH when no go.mod exists. The group here becomes ops.example.com. Avoid --group apps and other groups that clash with built-in API packages: the generated import collides with k8s.io/api/apps/v1 in every file that uses both. The layout puts types in api/v1/, controllers in internal/controller/, webhooks in internal/webhook/v1/, and the entry point in cmd/main.go. make manifests generates the CRD from Go types and markers, and RBAC from +kubebuilder:rbac comments, which produce rules like these:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: backup-operator
rules:
- apiGroups: ["ops.example.com"]
resources: ["backups"]
verbs: ["get", "list", "watch", "update", "patch"]
- apiGroups: ["ops.example.com"]
resources: ["backups/status"]
verbs: ["get", "update", "patch"]
- apiGroups: ["ops.example.com"]
resources: ["backups/finalizers"]
verbs: ["update"]
- apiGroups: ["batch"]
resources: ["cronjobs"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: [""]
resources: ["events"]
verbs: ["create", "patch"]
backups/finalizers is there because setting blockOwnerDeletion on a CronJob owned by a Backup requires permission to update the Backup’s finalizers. The reconcile follows the same steps every time: read, handle deletion, compute the desired state, act, record status.
import (
"context"
"time"
batchv1 "k8s.io/api/batch/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
logf "sigs.k8s.io/controller-runtime/pkg/log"
opsv1 "example.com/backup-operator/api/v1"
)
const snapshotFinalizer = "ops.example.com/snapshots"
func (r *BackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logf.FromContext(ctx)
var backup opsv1.Backup
if err := r.Get(ctx, req.NamespacedName, &backup); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
if !backup.DeletionTimestamp.IsZero() {
if controllerutil.ContainsFinalizer(&backup, snapshotFinalizer) {
if err := r.deleteSnapshots(ctx, &backup); err != nil {
return ctrl.Result{}, err
}
controllerutil.RemoveFinalizer(&backup, snapshotFinalizer)
if err := r.Update(ctx, &backup); err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
if controllerutil.AddFinalizer(&backup, snapshotFinalizer) {
if err := r.Update(ctx, &backup); err != nil {
return ctrl.Result{}, err
}
}
cron := &batchv1.CronJob{ObjectMeta: metav1.ObjectMeta{
Name: backup.Name + "-backup",
Namespace: backup.Namespace,
}}
op, err := controllerutil.CreateOrUpdate(ctx, r.Client, cron, func() error {
cron.Spec.Schedule = backup.Spec.Schedule
cron.Spec.Suspend = ptr.To(backup.Spec.Suspend)
r.setBackupContainer(&cron.Spec.JobTemplate.Spec.Template.Spec, &backup)
return controllerutil.SetControllerReference(&backup, cron, r.Scheme)
})
if err != nil {
return ctrl.Result{}, err
}
log.Info("reconciled backup CronJob", "operation", op)
meta.SetStatusCondition(&backup.Status.Conditions, metav1.Condition{
Type: "Ready",
Status: metav1.ConditionTrue,
Reason: "CronJobReconciled",
Message: "backup schedule is in place",
ObservedGeneration: backup.Generation,
})
backup.Status.ObservedGeneration = backup.Generation
if err := r.Status().Update(ctx, &backup); err != nil {
return ctrl.Result{}, err
}
return ctrl.Result{RequeueAfter: time.Hour}, nil
}
func (r *BackupReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&opsv1.Backup{}).
Owns(&batchv1.CronJob{}).
Named("backup").
Complete(r)
}
Each line carries a lesson:
- Logging.
logf.FromContext(ctx)returns a logger that already carries the controller, namespace and name. Kubebuilder reconcilers have noLogfield. - Imports. The custom API and
k8s.io/api/batch/v1get distinct aliases,opsv1andbatchv1. Two imports with the same name in one file do not compile. - Not found.
client.IgnoreNotFoundends quietly when the Backup is already gone; the garbage collector deletes its CronJob through the owner reference. - Finalizer. The operator adds its own finalizer and removes it only after
deleteSnapshotssucceeds, so a Backup cannot disappear while its snapshots still exist in storage. - Desired state.
CreateOrUpdatereads the CronJob, applies the mutate function, and writes only if something changed. Comparing whole specs withreflect.DeepEqualdoes not work: the API server fills defaults into a stored StatefulSet or CronJob spec, so it never equals the sparse spec the controller built, and the controller writes on every reconcile. Set only the fields you own, as here, wheresetBackupContaineredits the named container and the restart policy in place and leaves defaulted fields alone, or use server-side apply with a field manager; Kubebuilder 4.16 scaffolds an alpha server-side apply controller withcreate api --ssa. - Ownership.
SetControllerReferencefills in the owner’s uid and thecontrollerandblockOwnerDeletionflags, and returns an error if another controller already controls the CronJob. To test ownership elsewhere, usemetav1.GetControllerOformetav1.IsControlledByrather than checking for an emptyownerReferenceslist. - Status.
meta.SetStatusConditionupdates the existing condition of the same type and changeslastTransitionTimeonly when the status value changes, so conditions stay one per type.ObservedGenerationrecords which spec the condition describes. - Errors and requeues. Returning an error requeues the request with exponential backoff, and any
Resultreturned with it is ignored.RequeueAfterschedules the next run when the operator must check something outside the cluster.Result.Requeueis deprecated. The manager’s cache also resyncs every object on itsSyncPeriod, ten hours by default; do not depend on it for correctness.
Operator SDK builds on the same libraries and adds Helm and Ansible operator types; the Ansible plugin lives in its own repository, operator-framework/ansible-operator-plugins. Operator Lifecycle Manager v1, the operator-controller project with its ClusterExtension API and the catalogd catalog server, succeeds OLM v0’s Subscription and ClusterServiceVersion model for installing and upgrading operators from catalogs.
Choosing a tool
| Tool | What it does | Good fit |
|---|---|---|
| Helm chart | renders templates into manifests at install and upgrade time | packaging an application’s manifests with a few values |
| Operator | runs continuous logic against live state | stateful systems with upgrade, failover and backup procedures |
| Composition (kro) | defines an API whose instances expand into existing resources | giving teams one object that stands for several, without writing code |
A Helm chart is the simplest of the three and stops working once it has rendered: nothing reconciles the result until the next helm upgrade. An operator is the most capable and the most expensive, a program you must test, secure and upgrade, and it earns that cost when the job needs decisions a template cannot make. Composition tools sit between them. kro takes a ResourceGraphDefinition with a simple schema and a set of resource templates wired together with CEL expressions, registers a CRD for it, and reconciles each instance into the resources it describes. Reach for an operator only when the job needs logic that a composed set of resources cannot express.
kubectl --context kind-kx apply -f backup-crd.yamlkubectl --context kind-kx wait --for=condition=Established crd/backups.ops.example.comkubectl --context kind-kx api-resources --api-group=ops.example.comkubectl --context kind-kx explain backup.spec.targetkubectl --context kind-kx create namespace orderskubectl --context kind-kx apply -f orders-nightly.yamlkubectl --context kind-kx -n orders get backupskubectl --context kind-kx -n orders get backup orders-nightly -o jsonpath='{.spec.retentionDays}'kubectl --context kind-kx -n orders patch backup orders-nightly --type=merge -p '{"spec":{"database":"billing-db"}}'kubectl --context kind-kx -n orders patch backup orders-nightly --type=merge -p '{"spec":{"target":{"bucket":null}}}'kubectl --context kind-kx -n orders patch backup orders-nightly --subresource=status --type=merge -p '{"status":{"phase":"Scheduled"}}'kubectl --context kind-kx -n orders get backupskubectl --context kind-kx delete crd backups.ops.example.comkubectl --context kind-kx delete namespace orders
For your own kind cluster kx: copy a command and paste it into your terminal. Run in the simulator runs the same command in this page's simulated cluster instead; nothing on this page touches your machine. Save the CRD from this lesson as backup-crd.yaml and the Backup below as orders-nightly.yaml first. The default fills retentionDays with 7, both spec patches fail with the CEL messages, and the status patch fills the Phase column. Deleting the CRD deletes every Backup with it.
The orders-nightly.yaml used above:
apiVersion: ops.example.com/v1
kind: Backup
metadata:
name: orders-nightly
namespace: orders
spec:
database: orders-db
schedule: "0 2 * * *"
engineVersion: "17.4"
target:
kind: S3
bucket: orders-backupsActual state
Check your understanding
Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.
Lesson not yet reconciled
Desired: 4 objectives, 0 metReconciled: 4 of 4 objectives met
- Define a CRD with a structural schema, CEL validation rules and a status subresource. (not yet met)
- Explain served versus storage versions and when a conversion webhook is needed. (not yet met)
- Describe an operator's reconcile function and why it must be idempotent. (not yet met)
- Choose between an operator, a Helm chart and a composition tool for a job. (not yet met)
Pass every check above to reconcile this lesson.
Every check has passed, so the desired state is met. First-try accuracy: 0 of 6. This lesson's review cards are in your queue.
Practice
Put this lesson to work on the simulated cluster. Everything runs in your browser, with nothing to install.
Changed since the notes
This lesson draws on an earlier set of study notes. Where the documentation contradicts a claim in them, qualifies it or has moved past it, the claim is listed here with the corrected statement and the source it was checked against.
Show 15 corrections
The notes saidOpenAPI schemas can't express all constraints; complex validation needs webhooks.
CorrectedCRD validation rules in CEL (x-kubernetes-validations) are stable since Kubernetes 1.29 and handle cross-field rules and transition rules (oldSelf, e.g. immutability); validation ratcheting is GA in 1.33. Webhooks are only needed for checks that require external state or other objects.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidNo protobuf support. CRDs use JSON only.
CorrectedCRDs still do not support Protocol Buffers (aggregated APIs do). CBOR is being added as a second encoding: KEP-4222 alpha in 1.32 (CBORServingAndStorage gate, off by default, which also makes CBOR the storage encoding for custom resources) with beta listed for 1.37; the exact default state in 1.37 was not confirmed here.
The notes saidOnly one version can be storage; deprecate old versions before removing them.
CorrectedCorrect, plus: before removing a version, rewrite stored objects to the new storage version and remove the old version from the CRD's status.storedVersions. Built-in Storage Version Migration (storagemigration.k8s.io) went beta in 1.35 and GA (v1, enabled by default) in 1.37, replacing the out-of-tree migrator.
The notes saidkubectl apply --dry-run=server validates CRs.
CorrectedCorrect. Server-side field validation is GA since 1.27 and kubectl --validate defaults to strict, so unknown or duplicate fields are rejected (HTTP 400) instead of silently pruned; controllers default to Warn.
The notes saidSample Database uses version: "14" which fails the schema pattern '^\d+\.\d+$'.
CorrectedThe sample is rejected with 'spec.version in body should match '^\d+\.\d+$''. Use version: "14.0" or relax the pattern to '^\d+(\.\d+)?$'.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidSchema type list (string, integer, boolean, array, object) omits number.
CorrectedStructural schemas also support number (floating point; CEL type double) alongside integer, string, boolean, array and object; x-kubernetes-int-or-string and x-kubernetes-preserve-unknown-fields cover mixed/opaque values.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidScale subresource maps statusReplicasPath to .status.readyReplicas.
CorrectedstatusReplicasPath maps to scale.status.replicas and conventionally points to .status.replicas; labelSelectorPath (required for HPA/VPA) must point to a string field holding a serialized label selector (for example .status.labelSelector of type string), not a selector struct.
Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
The notes saidkubebuilder init --domain example.com; kubebuilder create api --group apps --version v1 --kind Database; generated layout.
CorrectedKubebuilder is v4 (v4.16.0, 2026-09-10, Kubernetes 1.37, controller-runtime v0.25). go/v4 is the default plugin; --repo <module path> is required outside GOPATH (no go.mod). Layout: api/<version>/, internal/controller/, internal/webhook/<version>/ (the --legacy webhook flag was removed in 4.16), cmd/main.go. Avoid --group apps, which collides with the core apps API in Go imports.
The notes saidOperator SDK supports Go, Ansible and Helm operators with OLM integration.
CorrectedOperator SDK is still released (v1.42.3, 2026-06-26) with Go, Ansible and Helm support, but the Ansible plugin is extracted to operator-framework/ansible-operator-plugins, and OLM v1 (operator-controller with the ClusterExtension API and catalogd) is the successor to OLM v0's Subscription/CSV model. Helm plugin location was not confirmed here.
The notes saidcontroller-runtime provides default metrics; periodic resync occurs; framework requeues with exponential backoff.
CorrectedCorrect with specifics: returning a non-nil error requeues with exponential backoff and the Result is ignored; Result.Requeue is deprecated (use RequeueAfter); the cache SyncPeriod defaults to 10 hours and the docs advise not to rely on or tune it casually. Current release v0.25.3.
The notes saidlog := r.Log.WithValues(…)
CorrectedCurrent Kubebuilder scaffolds have no Log field on the reconciler; they get a contextual logger with log := logf.FromContext(ctx) (sigs.k8s.io/controller-runtime/pkg/log), which already carries controller, namespace and name values.
The notes saidreflect.DeepEqual(existing.Spec, desired.Spec) on a StatefulSet decides whether to update.
CorrectedThe API server defaults many StatefulSet fields (podManagementPolicy, updateStrategy, revisionHistoryLimit, persistentVolumeClaimRetentionPolicy, container terminationMessagePath, etc.), so the stored spec never deep-equals an undefaulted desired spec and the controller updates every reconcile. Compare only the fields you own, use controllerutil.CreateOrUpdate with a mutate function, or use server-side apply (Kubebuilder 4.16 scaffolds alpha SSA with create api --ssa).
The notes saidStatus example appends a new Ready condition every reconcile with LastTransitionTime: metav1.Now().
CorrectedUse meta.SetStatusCondition(&obj.Status.Conditions, metav1.Condition{Type, Status, Reason, Message, ObservedGeneration: obj.Generation}): it updates the existing condition of that type and changes LastTransitionTime only when Status changes, so conditions stay one per type.
Sourcepkg.go.dev/k8s.io/apimachinery/pkg/api/meta#SetStatusCondition
The notes saidGo snippets use the single alias appsv1 for both the custom Database type and k8s.io/api/apps/v1.
CorrectedTwo imports with the same package name in one file do not compile ('appsv1 redeclared'). Alias them distinctly (for example dbv1 for the custom API and appsv1 for k8s.io/api/apps/v1) and choose a non-colliding --group.
The notes saidAdoption snippet ignores the r.Update error and checks OwnerReferences == nil.
CorrectedCheck metav1.GetControllerOf(obj) (or metav1.IsControlledBy) instead of a nil slice, set ownership with controllerutil.SetControllerReference (it errors if another controller already owns the object), and return the Update error so the request is retried.
Sourcepkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil#SetControllerReference
Every correction across the guide, by note and topic.
Sources
Checked against kubernetes.io and AWS documentation for Kubernetes 1.37 on .
- kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources
- kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
- kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning
- kubernetes.io/docs/reference/using-api/cel
- kubernetes.io/blog/2026/08/31/kubernetes-v1-37-storage-version-migration-ga
- kubernetes.dev/resources/keps/4222
- kubernetes.io/docs/concepts/extend-kubernetes/operator
- book.kubebuilder.io/quick-start.html
- github.com/kubernetes-sigs/kubebuilder/releases/tag/v4.16.0
- pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile
- pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil
- pkg.go.dev/k8s.io/apimachinery/pkg/api/meta
- github.com/operator-framework/operator-sdk/releases/tag/v1.42.3
- github.com/operator-framework/ansible-operator-plugins
- operator-framework.github.io/operator-controller
- kro.run/docs/overview
- docs.aws.amazon.com/eks/latest/userguide/capabilities.html
- docs.aws.amazon.com/eks/latest/userguide/ack-concepts.html
- docs.aws.amazon.com/eks/latest/userguide/kro-concepts.html
Custom resources and operators
↓ ↑ step, 1 to 7 scene, Esc leave