The API and the loopLesson 8 of 8
  1. Desired state and the reconcile loop, not reconciled
  2. Control plane and nodes, not reconciled
  3. API machinery: groups, versions and resource versions, not reconciled
  4. kubectl and kubeconfig, not reconciled
  5. Namespaces, labels and annotations, not reconciled
  6. Declarative management and server-side apply, not reconciled
  7. Owners, finalizers and garbage collection, not reconciled
  8. Custom resources and operators, not reconciled
    1. CRDs extend the API
    2. Schemas and validation
    3. Subresources and columns
    4. Versions and conversion
    5. The operator pattern
    6. Writing a reconcile
    7. Choosing a tool

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.

  • 30 min
  • 4 objectives
  • 7 scenes
  • Includes an On AWS layer

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:

Before the CRD exists, the API has no such resource
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. kubectl sends requests with --validate=strict by default, and server-side field validation, GA in Kubernetes 1.27, turns an unknown or duplicated field into a 400 error 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 without retentionDays reads back with 7.
  • Validation. OpenAPI keywords such as minimum, maxLength, enum and pattern check 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:

A built-in controller reconciling: one pod deleted, one pod created
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

propagationPolicy

The Deployment goes at once; the garbage collector deletes its dependents after.

Each action runs as a kubectl command; it shows here.

t = 0 s

Delivered changes
0 of 0

Watch stream0 queued

  1. Nothing queued, nothing in flight.

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.Step delivers the change at the head of the stream.

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.

Apply a Deployment and step through its watch stream, or scrub back through what was delivered. Each change names the component that wrote it, and each controller acts only on the difference between what is wanted and what exists.

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 no Log field.
  • Imports. The custom API and k8s.io/api/batch/v1 get distinct aliases, opsv1 and batchv1. Two imports with the same name in one file do not compile.
  • Not found. client.IgnoreNotFound ends 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 deleteSnapshots succeeds, so a Backup cannot disappear while its snapshots still exist in storage.
  • Desired state. CreateOrUpdate reads the CronJob, applies the mutate function, and writes only if something changed. Comparing whole specs with reflect.DeepEqual does 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, where setBackupContainer edits 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 with create api --ssa.
  • Ownership. SetControllerReference fills in the owner’s uid and the controller and blockOwnerDeletion flags, and returns an error if another controller already controls the CronJob. To test ownership elsewhere, use metav1.GetControllerOf or metav1.IsControlledBy rather than checking for an empty ownerReferences list.
  • Status. meta.SetStatusCondition updates the existing condition of the same type and changes lastTransitionTime only when the status value changes, so conditions stay one per type. ObservedGeneration records which spec the condition describes.
  • Errors and requeues. Returning an error requeues the request with exponential backoff, and any Result returned with it is ignored. RequeueAfter schedules the next run when the operator must check something outside the cluster. Result.Requeue is deprecated. The manager’s cache also resyncs every object on its SyncPeriod, 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

ToolWhat it doesGood fit
Helm chartrenders templates into manifests at install and upgrade timepackaging an application’s manifests with a few values
Operatorruns continuous logic against live statestateful systems with upgrade, failover and backup procedures
Composition (kro)defines an API whose instances expand into existing resourcesgiving 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.

A custom resource on your cluster

  1. kubectl --context kind-kx apply -f backup-crd.yaml
  2. kubectl --context kind-kx wait --for=condition=Established crd/backups.ops.example.com
  3. kubectl --context kind-kx api-resources --api-group=ops.example.com
  4. kubectl --context kind-kx explain backup.spec.target
  5. kubectl --context kind-kx create namespace orders
  6. kubectl --context kind-kx apply -f orders-nightly.yaml
  7. kubectl --context kind-kx -n orders get backups
  8. kubectl --context kind-kx -n orders get backup orders-nightly -o jsonpath='{.spec.retentionDays}'
  9. kubectl --context kind-kx -n orders patch backup orders-nightly --type=merge -p '{"spec":{"database":"billing-db"}}'
  10. kubectl --context kind-kx -n orders patch backup orders-nightly --type=merge -p '{"spec":{"target":{"bucket":null}}}'
  11. kubectl --context kind-kx -n orders patch backup orders-nightly --subresource=status --type=merge -p '{"status":{"phase":"Scheduled"}}'
  12. kubectl --context kind-kx -n orders get backups
  13. kubectl --context kind-kx delete crd backups.ops.example.com
  14. kubectl --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-backups

Actual state

Check your understanding

6 checks

Your first answer to each check is the one that counts. After a miss you can answer again; passing every check reconciles the lesson.

  1. Check 1 of 6

    The Backup CRD enables the status subresource. A client sends one update to the main endpoint that changes both spec.schedule and status.phase. What is stored?

  2. Check 2 of 6

  3. Check 3 of 6

    You add a CEL rule to a CRD, and some stored Backups already break it. A user then changes only the labels of one of those Backups. In Kubernetes 1.33 and later, what happens?

  4. Check 4 of 6

    Versions v1alpha1 and v1 of a CRD have identical schemas. Which conversion strategy does the CRD need?

  5. Check 5 of 6

    Why must a reconcile function be idempotent?

  6. Check 6 of 6

    Application teams need one object that creates a Deployment, a Service and an S3 bucket, kept reconciled by the cluster, with no custom logic beyond wiring values together. What fits best?

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
  1. Stale, true once, no longerCustom Resource Definitions

    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

  2. Nuance, true with conditionsCustom 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.

    Sourcekubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/%20;%20https://www.kubernetes.dev/resources/keps/4222

  3. Nuance, true with conditionsCustom Resource Definitions

    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.

    Sourcekubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning/%20;%20https://kubernetes.io/blog/2026/08/31/kubernetes-v1-37-storage-version-migration-ga

  4. Nuance, true with conditionsCustom Resource Definitions

    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.

    Sourcekubernetes.io/blog/2023/04/24/openapi-v3-field-validation-ga/%20;%20https://kubernetes.io/docs/reference/kubectl/generated/kubectl_apply

  5. Wrong, not trueCustom Resource Definitions

    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

  6. Wrong, not trueCustom 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

  7. Wrong, not trueCustom 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

  8. Nuance, true with conditionsBuilding Kubernetes Operators

    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.

    Sourcegithub.com/kubernetes-sigs/kubebuilder/releases/tag/v4.16.0%20;%20https://book.kubebuilder.io/quick-start.html

  9. Nuance, true with conditionsBuilding Kubernetes Operators

    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.

    Sourcegithub.com/operator-framework/operator-sdk/releases/tag/v1.42.3%20;%20https://github.com/operator-framework/ansible-operator-plugins

  10. Nuance, true with conditionsBuilding Kubernetes Operators

    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.

    Sourcepkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile#Result%20;%20https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/cache#Options

  11. Stale, true once, no longerBuilding Kubernetes Operators

    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.

    Sourcebook.kubebuilder.io/quick-start.html

  12. Wrong, not trueBuilding Kubernetes Operators

    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).

    Sourcegithub.com/kubernetes-sigs/kubebuilder/releases/tag/v4.16.0%20;%20https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil#CreateOrUpdate

  13. Wrong, not trueBuilding Kubernetes Operators

    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

  14. Wrong, not trueBuilding Kubernetes Operators

    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.

    Sourcego.dev/ref/spec#Import_declarations

  15. Wrong, not trueBuilding Kubernetes Operators

    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 .

  1. kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources
  2. kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions
  3. kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning
  4. kubernetes.io/docs/reference/using-api/cel
  5. kubernetes.io/blog/2026/08/31/kubernetes-v1-37-storage-version-migration-ga
  6. kubernetes.dev/resources/keps/4222
  7. kubernetes.io/docs/concepts/extend-kubernetes/operator
  8. book.kubebuilder.io/quick-start.html
  9. github.com/kubernetes-sigs/kubebuilder/releases/tag/v4.16.0
  10. pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile
  11. pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil
  12. pkg.go.dev/k8s.io/apimachinery/pkg/api/meta
  13. github.com/operator-framework/operator-sdk/releases/tag/v1.42.3
  14. github.com/operator-framework/ansible-operator-plugins
  15. operator-framework.github.io/operator-controller
  16. kro.run/docs/overview
  17. docs.aws.amazon.com/eks/latest/userguide/capabilities.html
  18. docs.aws.amazon.com/eks/latest/userguide/ack-concepts.html
  19. docs.aws.amazon.com/eks/latest/userguide/kro-concepts.html

Custom resources and operators

↓ ↑ step, 1 to 7 scene, Esc leave

kind cluster kxLast command: Nothing run yet