TExcelTAD
Home › Kubernetes › Custom Resources & CRDs

Custom Resources & CRDs

The Operators & CRDs lesson showed the big idea: a CustomResourceDefinition teaches the API server a new kind, and a controller reconciles objects of that kind. This lesson goes into the details you need when you design a CRD that other people will depend on for years: schemas the API server enforces, defaults, CEL validation rules, the status and scale subresources, versioning, finalizers and the conventions that make a controller behave well.

Anatomy of a production CRD

yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: backups.data.example.com            # must be <plural>.<group>
spec:
  group: data.example.com
  scope: Namespaced                          # or Cluster
  names:
    kind: Backup
    listKind: BackupList
    plural: backups
    singular: backup
    shortNames: [bk]
    categories: [all]                        # show up in `kubectl get all`
  versions:
    - name: v1
      served: true                           # the API answers on /apis/data.example.com/v1
      storage: true                          # exactly one version is stored in etcd
      subresources:
        status: {}                           # /status endpoint, spec and status updated separately
      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]
              properties:
                database: {type: string, minLength: 1, maxLength: 63}
                schedule: {type: string}
                retentionDays: {type: integer, minimum: 1, maximum: 365, default: 7}
                storageClass: {type: string, default: standard}
                target:
                  type: string
                  enum: [s3, gcs, azure]
              x-kubernetes-validations:
                - rule: "self.database == oldSelf.database"
                  message: database is immutable
                - rule: "self.target != 'azure' || self.retentionDays <= 90"
                  message: azure backups keep at most 90 days
            status:
              type: object
              x-kubernetes-preserve-unknown-fields: true

With that applied, kubectl get backups prints the printer columns (sample output):

text
NAME           DATABASE   SCHEDULE      PHASE       AGE
orders-daily   orders     0 2 * * *     Succeeded   12d
users-hourly   users      0 * * * *     Running     3h

What the API server does with the schema

CRDs in apiextensions.k8s.io/v1 must have a structural schema: every field has a type, and the server uses it for four things, in this order on every write:

Step Effect
Pruning Fields not in the schema are dropped (unless the subtree has x-kubernetes-preserve-unknown-fields: true). The client chooses how loudly: with fieldValidation=Warn (the server default) it gets a warning, with Strict (what kubectl sends by default) the request fails with strict decoding error: unknown field.
Defaulting Missing fields with a default are filled in, so retentionDays: 7 is stored even if the user omitted it.
OpenAPI validation Types, required, enum, minimum/maximum, minLength, pattern, maxItems…
CEL rules x-kubernetes-validations expressions, evaluated with self (and oldSelf on updates).

CEL rules (Common Expression Language) are what used to require a validating webhook: cross-field checks ("if target is azure, retention ≤ 90"), and transition rules that compare with the old object. A rule that mentions oldSelf is only checked on updates, which makes "immutable after creation" a one-liner. The model below runs the whole pipeline on a few objects, with the CEL expressions written as small Python functions:

python · try it yourself
SCHEMA = {
    "database": {"type": str, "required": True, "minLength": 1, "maxLength": 63},
    "schedule": {"type": str, "required": True},
    "retentionDays": {"type": int, "minimum": 1, "maximum": 365, "default": 7},
    "storageClass": {"type": str, "default": "standard"},
    "target": {"type": str, "enum": ["s3", "gcs", "azure"]},
}
RULES = [  # (needs oldSelf?, check, message), like x-kubernetes-validations
    (True, lambda new, old: new["database"] == old["database"], "database is immutable"),
    (False, lambda new, old: new.get("target") != "azure" or new["retentionDays"] <= 90,
     "azure backups keep at most 90 days"),
]

def admit(spec, old=None):
    warnings, errors = [], []
    pruned = {k: v for k, v in spec.items() if k in SCHEMA}          # 1. pruning
    for k in spec.keys() - SCHEMA.keys():
        warnings.append(f'unknown field "spec.{k}"')
    for k, rule in SCHEMA.items():                                   # 2. defaulting
        if k not in pruned and "default" in rule:
            pruned[k] = rule["default"]
    for k, rule in SCHEMA.items():                                   # 3. OpenAPI checks
        if k not in pruned:
            if rule.get("required"):
                errors.append(f"spec.{k}: Required value")
            continue
        v = pruned[k]
        if type(v) is not rule["type"]:
            errors.append(f"spec.{k}: Invalid value: must be of type {rule['type'].__name__}")
        elif "enum" in rule and v not in rule["enum"]:
            errors.append(f'spec.{k}: Unsupported value: "{v}"')
        elif "maximum" in rule and v > rule["maximum"]:
            errors.append(f"spec.{k}: must be less than or equal to {rule['maximum']}")
    if not errors:                                                   # 4. CEL rules
        for needs_old, check, msg in RULES:
            if needs_old and old is None:
                continue                      # transition rules only run on update
            if not check(pruned, old):
                errors.append(f"spec: Invalid value: {msg}")
    return pruned, warnings, errors

stored = None
cases = [
    ("create", {"database": "orders", "schedule": "0 2 * * *", "retension": 30}),
    ("update", {"database": "orders", "schedule": "0 3 * * *", "retentionDays": 30}),
    ("update", {"database": "orders-v2", "schedule": "0 3 * * *"}),
    ("update", {"database": "orders", "schedule": "0 3 * * *", "target": "azure", "retentionDays": 120}),
    ("update", {"database": "orders", "schedule": "0 3 * * *", "target": "tape"}),
]
for verb, spec in cases:
    result, warnings, errors = admit(spec, stored)
    for w in warnings:
        print(f"  Warning: {w}")
    if errors:
        print(f"{verb}: REJECTED -> {'; '.join(errors)}")
    else:
        stored = result
        print(f"{verb}: stored {stored}")
  Warning: unknown field "spec.retension"
create: stored {'database': 'orders', 'schedule': '0 2 * * *', 'retentionDays': 7, 'storageClass': 'standard'}
update: stored {'database': 'orders', 'schedule': '0 3 * * *', 'retentionDays': 30, 'storageClass': 'standard'}
update: REJECTED -> spec: Invalid value: database is immutable
update: REJECTED -> spec: Invalid value: azure backups keep at most 90 days
update: REJECTED -> spec.target: Unsupported value: "tape"

The first create (sent with Warn validation) kept the misspelled retension out of etcd with a warning and filled in both defaults. The second update failed the transition rule, and the last one never reached CEL because the enum check failed first.

Tip: Keep CEL rules cheap. The API server estimates each rule's worst-case cost from the schema (that's why maxLength and maxItems matter) and rejects a CRD whose rules could be too expensive.

Status, generation and conditions

With subresources.status enabled, users write spec and the controller writes status through a separate endpoint, so neither can clobber the other. The API server also bumps metadata.generation on every spec change (not on status changes). A well-behaved controller copies the generation it acted on into status.observedGeneration and reports standard conditions:

yaml
status:
  observedGeneration: 4
  phase: Succeeded
  lastBackupTime: "2026-10-17T02:00:41Z"
  conditions:
    - type: Ready
      status: "True"
      reason: BackupCompleted
      observedGeneration: 4
      lastTransitionTime: "2026-10-17T02:00:41Z"
      message: 2.1 GiB written to s3://acme-backups/orders

Tools such as kubectl wait --for=condition=Ready backup/orders-daily and Argo CD's health checks rely on exactly this shape. observedGeneration < generation means "the controller hasn't caught up with your last edit yet".

The scale subresource (specReplicasPath, statusReplicasPath, labelSelectorPath) lets kubectl scale and the HorizontalPodAutoscaler from Autoscaling drive your custom kind.

Finalizers and deletion

Deleting an object that has entries in metadata.finalizers does not remove it: the API server only sets deletionTimestamp. The controller sees that, cleans up what lives outside the cluster (the files in the bucket, a DNS record, a cloud database), removes its finalizer, and only then the object disappears. Objects inside the cluster are better cleaned up by ownerReferences and the garbage collector. This loop models a backup controller handling a spec change, a failure with requeue, and a deletion:

python · try it yourself
FINALIZER = "data.example.com/cleanup"
bucket = set()

def reconcile(obj, storage_ok=True):
    meta, status = obj["metadata"], obj["status"]
    if meta.get("deletionTimestamp"):
        if FINALIZER in meta["finalizers"]:
            bucket.discard(obj["spec"]["database"])
            meta["finalizers"].remove(FINALIZER)
            return "external files deleted, finalizer removed -> object goes away"
        return "nothing to do"
    if FINALIZER not in meta["finalizers"]:
        meta["finalizers"].append(FINALIZER)
        return "added finalizer, requeue"
    if status.get("observedGeneration") == meta["generation"]:
        return "up to date (no-op)"
    if not storage_ok:
        status["conditions"] = [{"type": "Ready", "status": "False", "reason": "StorageUnavailable"}]
        return "error: storage unavailable, requeue with back-off"
    bucket.add(obj["spec"]["database"])
    status.update(observedGeneration=meta["generation"], phase="Scheduled",
                  conditions=[{"type": "Ready", "status": "True", "reason": "Scheduled"}])
    return f"scheduled {obj['spec']['schedule']} for generation {meta['generation']}"

bk = {"metadata": {"name": "orders-daily", "generation": 1, "finalizers": []},
      "spec": {"database": "orders", "schedule": "0 2 * * *"}, "status": {}}

events = [("created", True), ("resync", True), ("resync", True),
          ("spec edited", False), ("retry", True), ("delete requested", True)]
for event, ok in events:
    if event == "spec edited":
        bk["spec"]["schedule"] = "0 3 * * *"
        bk["metadata"]["generation"] += 1
    if event == "delete requested":
        bk["metadata"]["deletionTimestamp"] = "2026-10-18T09:00:00Z"
    print(f"{event:17} gen={bk['metadata']['generation']} -> {reconcile(bk, ok)}")
print("finalizers:", bk["metadata"]["finalizers"], "| bucket:", sorted(bucket))
created           gen=1 -> added finalizer, requeue
resync            gen=1 -> scheduled 0 2 * * * for generation 1
resync            gen=1 -> up to date (no-op)
spec edited       gen=2 -> error: storage unavailable, requeue with back-off
retry             gen=2 -> scheduled 0 3 * * * for generation 2
delete requested  gen=2 -> external files deleted, finalizer removed -> object goes away
finalizers: [] | bucket: []

Notice the controller is level-triggered: it never asks "what changed?", it compares the whole desired state with reality, so a missed event or a crash in the middle is harmless.

Note: A finalizer whose controller is gone blocks deletion forever (the object, and its namespace, stay Terminating). Uninstall CRs before the operator, and only remove a finalizer by hand once you know the external resource is gone.

Versioning a CRD

APIs evolve: v1alpha1 → v1beta1 → v1. A CRD can serve several versions at once, but only one is the storage version. When the versions have different shapes, a conversion webhook (spec.conversion.strategy: Webhook) translates between them; with strategy: None the server only swaps the apiVersion string. The usual design is hub and spoke: every version converts to and from the storage version, and conversions must round-trip without loss (unknown data is parked in annotations).

python · try it yourself
def v1alpha1_to_v1(obj):        # spoke -> hub
    spec = dict(obj["spec"])
    spec["retentionDays"] = spec.pop("keepWeeks", 1) * 7
    return {"apiVersion": "data.example.com/v1", "spec": spec}

def v1_to_v1alpha1(obj):        # hub -> spoke
    spec = dict(obj["spec"])
    days = spec.pop("retentionDays")
    spec["keepWeeks"] = days // 7
    ann = {} if days % 7 == 0 else {"data.example.com/retention-days": str(days)}
    return {"apiVersion": "data.example.com/v1alpha1", "spec": spec, "annotations": ann}

def v1alpha1_back(obj):         # restore the lossy part when converting back
    hub = v1alpha1_to_v1(obj)
    if "data.example.com/retention-days" in obj.get("annotations", {}):
        hub["spec"]["retentionDays"] = int(obj["annotations"]["data.example.com/retention-days"])
    return hub

old_client = {"apiVersion": "data.example.com/v1alpha1", "spec": {"database": "orders", "keepWeeks": 2}}
print("stored as v1:   ", v1alpha1_to_v1(old_client))
stored = {"apiVersion": "data.example.com/v1", "spec": {"database": "users", "retentionDays": 10}}
served = v1_to_v1alpha1(stored)
print("served v1alpha1:", served)
print("round trip ok:  ", v1alpha1_back(served) == stored)
stored as v1:    {'apiVersion': 'data.example.com/v1', 'spec': {'database': 'orders', 'retentionDays': 14}}
served v1alpha1: {'apiVersion': 'data.example.com/v1alpha1', 'spec': {'database': 'users', 'keepWeeks': 1}, 'annotations': {'data.example.com/retention-days': '10'}}
round trip ok:   True

After a storage-version change, objects already in etcd stay in the old version until they are rewritten. Run a storage migration (rewrite every object, or use the StorageVersionMigration API where available), and only then remove the old version from status.storedVersions and stop serving it.

Design checklist

  • Put user intent in spec, observations in status; never let the controller write spec.
  • Use defaults and CEL rules in the schema instead of a webhook whenever you can (no extra service to keep alive; see Admission Control & Policies).
  • Add printer columns and categories; set observedGeneration and Ready conditions.
  • Version from day one (v1alpha1), and plan conversions before you need them.
  • Grant the controller RBAC for backups and backups/status, and users only for backups (RBAC).

Learn more: Operators & CRDs · Objects & Manifests · GitOps

Test yourself

A client sends a custom resource with a field that is not in the CRD's structural schema, using the server's default field validation (Warn). What happens?

  1. The request fails with a 500 error
  2. The field is pruned (dropped) and the client gets a warning
  3. The field is stored as-is
  4. The CRD is deleted

Which CEL rule makes spec.database immutable after creation?

  1. self.database != ''
  2. self.database == oldSelf.database
  3. has(self.database)
  4. self.database.size() < 63

What does status.observedGeneration < metadata.generation tell you?

  1. The object is being deleted
  2. The controller has not yet processed the latest spec change
  3. The CRD has two storage versions
  4. The status subresource is disabled