A CRD teaches the Kubernetes API server a new noun, and that's all it does: persistence, validation, RBAC, kubectl integration, and watch semantics all come for free. Behavior requires a controller (section 3.3). Keeping schema and behavior cleanly separated in your head unlocks the rest of domain 3.

needsmake upmake api

Orientation

competency 3.1 · designing and creating CRDs

Nothing on this page needs a running controller; the whole point is seeing how much a CRD gives you all by itself. Apply one and you immediately get a typed, validated, RBAC-aware, watchable, kubectl explain-documented API with zero behavior behind it. That clean seam is where platform engineering lives.

What a task looks like

"Create a CRD for X with required field Y, an enum, and a printer column; create one valid instance; show that an invalid one is rejected." Every clause is graded by an object or an error message. Writing a CRD from scratch under time pressure takes muscle memory, so type one out by hand at least three times before exam day.

Anatomy: the fields that matter

group · names · scope · versions

Every CRD comes down to four structural pieces: group, names (plural, singular, kind, shortNames, categories), scope (Namespaced or Cluster), and versions[]. Watch out for metadata.name: it isn't free-form. It must be exactly <plural>.<group>, and mistyping it is the most common first error.

FieldWhy it matters
scopeNamespaced unlocks per-namespace RBAC and ResourceQuota via count/<plural>.<group>. Cluster-scoped objects can't be owned by namespaced ones, a real design constraint you'll see again in Crossplane (3.5).
names.shortNamesCluster-global and first-come. If two CRDs both claim tb, kubectl prints a collision warning; as a platform API author, you own avoiding those clashes.
names.categoriesDrops your kind into groupings like kubectl get all (or a custom kubectl get platform). Cheap usability win.
versions[].servedControls whether the API server serves requests for this version at all.
versions[].storageMarks the single version persisted in etcd; all other served versions convert on the fly.
versions[].deprecatedSends a deprecation warning header to clients using this version, the polite way to sunset an API.

Versioning at exam depth: deprecating an old version means keeping served: true while moving storage: true to the new version; retiring it means flipping served: false. That's the entire story whenever schemas match (strategy: None). When schemas actually diverge, you need a Webhook converter to transform objects on the fly. Know both options and what each one costs.

Schema: where design happens

CRD schemas use OpenAPI v3: types, required, enum, pattern, minimum/maximum, default, and format. Keep these Kubernetes extensions on your radar:

  • x-kubernetes-validations: CEL rules with custom error messages evaluated right inside the API server. This gives you cross-field checks (self.max >= self.min) and immutability (self == oldSelf) with zero webhooks to run. Users see your message directly in their terminal, so write it clearly.
  • x-kubernetes-preserve-unknown-fields: opts a subtree out of schema pruning. By default, any field missing from the schema is silently stripped on write, which looks like data loss until you realize the schema is doing its job.
  • Also handy: x-kubernetes-list-type: map paired with x-kubernetes-list-map-keys (so server-side apply merges lists cleanly instead of replacing them wholesale), and x-kubernetes-int-or-string.
Pruning isn't an error

The API server drops any field your schema didn't declare. kubectl's default strict field validation catches that and throws an error (strict decoding error: unknown field), but any client skipping validation (--validate=false, many controllers, raw API calls) loses the field silently with no warning and no event. Users swear "my setting is being ignored", when in fact etcd never stored it. That's why slapping preserve-unknown-fields on a platform API is usually a trap: you're trading a loud, helpful rejection for silent misconfiguration.

Subresources and presentation

  • subresources.status splits /status into its own API endpoint, and that boundary cuts both ways: writes to the main resource ignore .status, while writes to /status ignore .spec. That's why the classic "my controller's status updates keep vanishing" bug is actually the subresource working: the caller used Update() instead of UpdateStatus() (or forgot --subresource=status on kubectl patch). Without it, anyone editing spec can clobber controller status, which is why every operator convention in section 3.3 relies on it.
  • subresources.scale wires kubectl scale and HPAs straight into your custom kind with three JSONPaths.
  • additionalPrinterColumns controls what kubectl get displays. As section 3.1 noted, a platform API without a clear READY column makes users miserable.

Once you apply a CRD, wait for its Established condition; until then, requests for the new kind can 404. Right after that, your custom noun acts like a native Kubernetes type: RBAC rules can grant it, ResourceQuota can count/ it, admission webhooks and policy engines see it, and kubectl explain renders the descriptions you wrote. Those descriptions aren't busywork; they're the live docs your developers actually read.

Where CRDs stop

and what you reach for instead
  • Aggregated API servers: for custom storage backends, massive object counts, or non-etcd persistence. Good to recognize in docs, almost never the right exam pick.
  • Admission webhooks: for validation that CEL can't do (like cross-object lookups) or complex mutation. Remember the cost: every webhook becomes an availability dependency on the API server, and failurePolicy is where you pick your failure mode (section 5.2).
  • Operators: for actual behavior. A CRD without a controller is just a typed ConfigMap, which is occasionally fine on its own (Crossplane XRs, Argo Applications, and Tekton Tasks are all declarative data driven by controllers running elsewhere).
  • Generators: Crossplane's XRD and kro's ResourceGraphDefinition both generate CRDs behind the scenes. Sections 3.5 and 3.6 build directly on what you're hand-writing right here.
Command reflex on an unfamiliar cluster

Run kubectl api-resources | grep <tool> to discover the nouns, kubectl explain <kind> --recursive to inspect the schema, and kubectl get crd <name> -o yaml to check printer columns, versions, and validation rules. Those three commands let you operate an operator you've never seen before, a classic exam move.

Schema mechanics the API server enforces

structural rules · CEL in detail · ratcheting · defaulting and nullable · list types

Structural schema: the four rules

apiextensions.k8s.io/v1 mandates a structural schema. If your CRD violates it, create fails with a Required value error pointing at the node missing a type (legacy CRDs migrated from v1beta1 surface a NonStructuralSchema condition instead and forfeit pruning, defaulting, and CEL). The four rules are straightforward: every node (root, every property, every array item) must declare a non-empty type unless it sets x-kubernetes-int-or-string: true or x-kubernetes-preserve-unknown-fields: true; anything referenced inside allOf, anyOf, oneOf, or not must also be declared outside it; description, type, default, additionalProperties, and nullable can't live inside those junctors; and metadata can only constrain name and generateName. Nine times out of ten, a hand-written CRD fails because a nested property two levels down forgot its type.

Pruning and its exceptions

Unknown fields get pruned on every write across every version. Setting x-kubernetes-preserve-unknown-fields: true keeps arbitrary fields under that node, though pruning turns right back on for any child properties you explicitly declare inside it. x-kubernetes-embedded-resource: true marks a field that embeds a full Kubernetes object (so apiVersion, kind, and metadata are validated). Because kubectl apply runs strict field validation by default, it rejects unknown fields before pruning ever happens, explaining why the same YAML fails from your laptop yet silently succeeds when applied by a controller without strict validation.

CEL rules, all the fields

  • rule is scoped to whichever schema node holds x-kubernetes-validations, and self refers to that node. Putting a rule at the root lets you inspect both self.spec and self.status; lower down you only see that subtree. From metadata, CEL can only read apiVersion, kind, metadata.name, and metadata.generateName.
  • message gives a static error string, while messageExpression evaluates a CEL string dynamically (wrap numbers in string(x) to concatenate; falls back to message if evaluation errors). Skip both and Kubernetes prints a raw failed rule: <expression>.
  • reason picks the API status reason (FieldValueInvalid by default, or FieldValueForbidden, FieldValueRequired, FieldValueDuplicate), and fieldPath sets a relative JSON path so the error highlights the exact offending field rather than the parent block.
  • Transition rules (any rule referencing oldSelf) only fire on updates where both old and new values exist, and only along correlatable paths (object parents or x-kubernetes-list-type: map lists, never set or atomic). Core idioms: immutability self == oldSelf, append-only self.all(e, e in oldSelf), monotonic growth self >= oldSelf. Add optionalOldSelf: true to turn oldSelf into a CEL optional so the rule also runs on create and on newly populated fields.
  • Property names that clash with CEL keywords or contain -, ., or / get escaped: self.__namespace__, self.x__dash__prop.
  • Cost budget: Kubernetes statically estimates CEL cost when you apply the CRD. Looping over an unbounded list or string assumes worst-case sizes and fails with "CEL rule exceeded budget by more than 100x (try simplifying the rule, or adding maxItems, maxProperties, and maxLength where arrays, maps, and strings are used)". Add those bounds and the exact same rule passes (there's also a per-CRD total and runtime cap).
  • Compile-time errors that reject the CRD itself: no_matching_overload (like comparing an int to a bool), no_such_field (misspelled property), and invalid argument to has() macro.
  • Type gotchas: OpenAPI integer maps to 64-bit int while number maps to double (so self.replicas > 1.5 against an integer fails to compile). format: date-time becomes a timestamp, format: duration a duration, maps come from additionalProperties, and listType: set or map compares unordered.

Validation ratcheting (GA since 1.33)

When you tighten a CRD schema, an update to an existing object still succeeds as long as it doesn't touch the already-invalid field, letting you roll out stricter validation without migrating every stored object up front. Know the exceptions where ratcheting doesn't apply: transition rules using oldSelf, changes to x-kubernetes-list-type, additions to required, renamed properties, metadata rules, and any create request. Pair it with optionalOldSelf when you want explicit grandfathering rules.

Defaulting and nullable

  • Defaults are applied on incoming requests (in the request version), when reading stored objects back from etcd (storage version), and right after a mutating webhook patches an object. Read-time defaults aren't persisted back to etcd until the next write.
  • A default on a composite/object field has to pass the schema itself and is pruned of any unknown keys.
  • With nullable: false (default), an explicit null gets stripped and replaced by default if one is defined. With nullable: true, null is preserved as null and never defaulted. So foo: null with default: "x" only turns into "x" when the field isn't nullable.
  • Defaulting is another reason the status subresource matters: defaulting fields inside status can confuse controllers tracking generation changes.

List semantics

x-kubernetes-list-type: atomic (the default for primitive and struct lists) means server-side apply replaces the entire array under a single field manager. set merges unique scalar items. map paired with x-kubernetes-list-map-keys: [name] keys entries by field so multiple field managers can each own their own list items, and lets CEL correlate elements across updates (conditions lists use map keyed on type). Both Argo CD and Flux server-side apply treat atomic lists as all-or-nothing, which is why forgetting list-type: map causes "my injected sidecar keeps disappearing" bugs.

The error you'll read most

Learn to recognize all four rejection styles on sight: spec.tier: Unsupported value: "platinum": supported values: "bronze", "silver", "gold" is an enum; spec.sizeGB: Invalid value: 900: spec.sizeGB in body should be less than or equal to 500 is a numeric bound; spec: Invalid value: ...: bronze tier is capped at 50GB is your CEL rule; and strict decoding error: unknown field "spec.color" is kubectl's strict validation before the schema even ran. Spotting which validator spoke tells you the exact line of the CRD to edit.

Versions, subresources and the CRD-level errors

conversion · storedVersions · selectableFields · printer columns · scale · what kubectl says when the CRD itself is wrong

Versions in practice

  • Exactly one version carries storage: true, while any number can be served: true. When you don't specify a version, kubectl picks the highest-priority served version: GA (v2, v1) beats beta beats alpha, higher numbers first, so v1 beats v1beta1 beats v2alpha1.
  • Setting deprecated: true with a deprecationWarning attaches a warning header to every request on that version (which kubectl prints). Flipping served: false shuts down the endpoint, though existing objects stored at that version remain untouched in etcd.
  • spec.conversion.strategy: None simply rewrites apiVersion and assumes compatible schemas. Webhook sends a ConversionReview batch to your conversion service, which can transform anything except metadata (beyond labels and annotations).
  • Etcd only rewrites stored objects to the new storage version when those objects are next updated. status.storedVersions tracks every version that might still have bytes on disk, and Kubernetes blocks you from dropping a version from spec.versions while it's still listed there. Migrate cleanly using a StorageVersionMigration (storagemigration.k8s.io) or a no-op update loop over every object, then patch status.storedVersions.

Subresources, precisely

  • subresources.status: {} separates .status onto its own endpoint (main writes ignore status; /status writes ignore spec and validate only status) and ensures metadata.generation only increments when spec changes. Without it, every status update bumps generation and observedGeneration becomes useless.
  • subresources.scale takes specReplicasPath (under .spec, required), statusReplicasPath (under .status, required), and labelSelectorPath (string holding a serialized selector, required for HPA). Once wired, kubectl scale, HPA, and VPA all work natively on your CRD.
  • selectableFields (GA since 1.32) declares up to 8 scalar jsonPath fields per version under spec.versions[].selectableFields[], unlocking server-side filtering like kubectl get shirts --field-selector spec.color=blue so controllers and humans don't have to mirror spec fields into labels.

Printer columns and names

Each entry in additionalPrinterColumns[] sets name, type (integer, number, string, boolean, or date), optional format, jsonPath, description, and priority (0 appears in default output; > 0 appears only with -o wide). Using type: date formats timestamps as human-friendly ages. Because NAME is automatic while AGE isn't, most CRDs add {name: Age, type: date, jsonPath: .metadata.creationTimestamp}. Columns are per version, so v1alpha1 and v1 can render differently. names.shortNames are cluster-global and first-come; names.categories: [all] adds your kind to kubectl get all, and defining your own category (like fluxcd or platform) lets kubectl get platform -A show every kind you ship at once.

Lifecycle of the CRD object itself

  • Wait for Established: True and NamesAccepted: True right after applying; requests before then 404. If NamesAccepted is False citing "is already in use", your plural, kind, or shortName collided with an existing CRD.
  • Deleting a CRD deletes every custom resource of that kind across the cluster. The customresourcecleanup.apiextensions.k8s.io finalizer holds the CRD in Terminating until all CRs are gone, so a single stuck CR (say, a finalizer owned by a dead controller) pins the CRD too. Both Argo CD and Flux will happily prune a CRD if you remove its file unless you shield it (Prune=false or kustomize.toolkit.fluxcd.io/prune: disabled), easily the most destructive prune mistake you can make.
  • ResourceQuotas count CRs via count/<plural>.<group>, and RBAC targets them with apiGroups: [group] and resources: [plural, plural/status].

Errors from applying the CRD, and their causes

Message containsCause
metadata.name: Invalid value: must be spec.names.plural+"."+spec.groupCRD name doesn't match <plural>.<group>
spec.versions: Invalid value: must have exactly one version marked as storage versionZero or more than one version has storage: true
spec.versions[0].schema.openAPIV3Schema: Required value: schemas are requiredA v1 CRD version is missing its schema
must be structural / must not be inside allOf / NonStructuralSchema conditionViolation of one of the four structural schema rules above
compilation failed: ERROR: ... found no matching overload / undefined fieldCEL type mismatch or typo in a property name
CEL rule exceeded budgetUnbounded iteration: add maxItems, maxProperties, or maxLength
spec.conversion.webhook: Required value when strategy is WebhookSet strategy: Webhook without webhook.clientConfig and conversionReviewVersions
status.storedVersions[0]: Invalid value: must appear in spec.versionsDropped a version that objects may still be persisted at
additionalPrinterColumns[1].jsonPath: Invalid valueMalformed JSONPath or missing leading .
Reflex

Use kubectl explain <kind> --recursive and kubectl explain <kind>.spec.<field> to inspect live schemas and field docs (pass --api-version group/v1beta1 for older versions). Whenever a brand-new CRD "doesn't work", run kubectl get crd <name> -o jsonpath='{.status.conditions}' first, and always check {.status.storedVersions} before deleting an old version.

Exercises

tick the dot when its check passes

Type this platform-style CRD out by hand instead of copy-pasting; on exam day you get a prompt, not a template file:

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: tenantbuckets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket, shortNames: [tb] }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      subresources: { status: {} }
      additionalPrinterColumns:
        - { name: Tier,     type: string,  jsonPath: .spec.tier }
        - { name: SizeGB,   type: integer, jsonPath: .spec.sizeGB }
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: [tier]
              properties:
                tier:   { type: string, enum: [bronze, silver, gold], description: "Service tier; sets replication and backup policy." }
                sizeGB: { type: integer, minimum: 1, maximum: 500, default: 10 }
              x-kubernetes-validations:
                - rule: "self.tier != 'bronze' || self.sizeGB <= 50"
                  message: "bronze tier is capped at 50GB"
            status:
              type: object
              properties:
                phase: { type: string }

Apply it, then make the API server prove each design decision:

kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local
kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
kubectl get tb    # printer columns show Tier and SizeGB; apply one without sizeGB to watch the default appear
outputcaptured 2026-08-26
$ kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local condition met
$ kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
tenantbucket.platform.lab.local/good created
$ kubectl get tb    # printer columns show Tier and SizeGB; apply one without sizeGB to watch the default appear
Warning: short name "tb" could also match lower priority resource triggerbindings.triggers.tekton.dev
NAME   TIER     SIZEGB
good   silver   100

If cicd is installed, that last command also warns that tb could match Tekton's triggerbindings. Leave it as is; it's a live reminder that short names are cluster-global and first-come.

verify: test all three rejections, which are the real proof of your schema: tier: platinum fails on the enum, sizeGB: 900 fails on the maximum, and tier: bronze, sizeGB: 100 trips your CEL rule with your custom message. Three validators, three distinct error shapes: know which produced which.

Apply a TenantBucket carrying an undeclared field spec.color: red, read kubectl's strict decoding error, then reapply with --validate=false and read the object back; the field vanished silently with zero error. Finish with kubectl explain tenantbucket.spec --recursive to see your schema descriptions acting as live CLI docs.

verify: you can name the schema extension that preserves unknown fields, and explain why most platform APIs shouldn't use it.

Run kubectl patch tenantbucket good --subresource=status --type=merge -p '{"status":{"phase":"Ready"}}', verify kubectl get tb good -o jsonpath='{.status.phase}' prints Ready, and confirm a plain spec edit leaves that status intact.

verify: status survives spec updates and vice versa, the exact foundation every operator in section 3.3 depends on.

Inspect kubectl get crd appenvironments.platform.lab.local -o yaml (generated by Crossplane from our lab's XRD). Compare its schema and printer columns against yours and spot what a production-grade generated API adds (conditions conventions, connection details).

verify: pick three good patterns to borrow and fold at least one into your TenantBucket CRD.

A CRD's metadata.name isn't arbitrary text; it must equal <plural>.<group>. Trigger the error once so you recognize it instantly if you mistype a CRD name under exam time pressure.

kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: buckets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec: { type: object }
EOF
outputcaptured 2026-09-13
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: buckets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec: { type: object }
EOF
The CustomResourceDefinition "buckets.platform.lab.local" is invalid: metadata.name: Invalid value: "buckets.platform.lab.local": must be spec.names.plural+"."+spec.group
verify: the rejection explicitly quotes spec.names.plural+"."+spec.group as the required naming format.

Only one version at a time owns the bytes stored in etcd. Marking two versions with storage: true is behind half of all botched version migrations, and Kubernetes blocks it immediately on apply.

kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: twostore.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: twostore, singular: twostore, kind: TwoStore }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema: { type: object, properties: { spec: { type: object } } }
    - name: v1beta1
      served: true
      storage: true
      schema:
        openAPIV3Schema: { type: object, properties: { spec: { type: object } } }
EOF
outputcaptured 2026-09-13
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: twostore.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: twostore, singular: twostore, kind: TwoStore }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema: { type: object, properties: { spec: { type: object } } }
    - name: v1beta1
      served: true
      storage: true
      schema:
        openAPIV3Schema: { type: object, properties: { spec: { type: object } } }
EOF
The CustomResourceDefinition "twostore.platform.lab.local" is invalid: 
* spec.versions: Invalid value: [{"Name":"v1alpha1","Served":true,"Storage":true,"Deprecated":false,"DeprecationWarning":null,"Schema":null,"Subresources":null,"AdditionalPrinterColumns":null,"SelectableFields":null},{"Name":"v1beta1","Served":true,"Storage":true,"Deprecated":false,"DeprecationWarning":null,"Schema":null,"Subresources":null,"AdditionalPrinterColumns":null,"SelectableFields":null}]: must have exactly one version marked as storage version
* status.storedVersions: Invalid value: ["v1alpha1"]: must have the storage version v1beta1
verify: the API server rejects the CRD stating that exactly one version must be marked as the storage version.

Because CEL runs inside the API server on every write, Kubernetes enforces a strict cost budget at CRD creation time. Looping over an unbounded list trips that budget right away; adding maxItems and maxLength makes the exact same rule pass.

kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: budgets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: budgets, singular: budget, kind: Budget }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                names:
                  type: array
                  items: { type: string }
                  x-kubernetes-validations:
                    - rule: "self.all(x, x.contains('a'))"
EOF
kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: budgets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: budgets, singular: budget, kind: Budget }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                names:
                  type: array
                  maxItems: 10
                  items: { type: string, maxLength: 32 }
                  x-kubernetes-validations:
                    - rule: "self.all(x, x.contains('a'))"
EOF
kubectl delete crd budgets.platform.lab.local
outputcaptured 2026-09-13
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: budgets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: budgets, singular: budget, kind: Budget }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                names:
                  type: array
                  items: { type: string }
                  x-kubernetes-validations:
                    - rule: "self.all(x, x.contains('a'))"
EOF
The CustomResourceDefinition "budgets.platform.lab.local" is invalid: 
* spec.validation.openAPIV3Schema.properties[spec].properties[names].x-kubernetes-validations[0].rule: Forbidden: estimated rule cost exceeds budget by factor of more than 100x (try simplifying the rule, or adding maxItems, maxProperties, and maxLength where arrays, maps, and strings are declared)
* spec.validation.openAPIV3Schema.properties[spec].properties[names].x-kubernetes-validations[0].rule: Forbidden: contributed to estimated rule cost total exceeding cost limit for entire OpenAPIv3 schema
* spec.validation.openAPIV3Schema: Forbidden: x-kubernetes-validations estimated rule cost total for entire OpenAPIv3 schema exceeds budget by factor of more than 100x (try simplifying the rule, or adding maxItems, maxProperties, and maxLength where arrays, maps, and strings are declared)
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: budgets.platform.lab.local
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: budgets, singular: budget, kind: Budget }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              properties:
                names:
                  type: array
                  maxItems: 10
                  items: { type: string, maxLength: 32 }
                  x-kubernetes-validations:
                    - rule: "self.all(x, x.contains('a'))"
EOF
customresourcedefinition.apiextensions.k8s.io/budgets.platform.lab.local created
$ kubectl delete crd budgets.platform.lab.local
customresourcedefinition.apiextensions.k8s.io "budgets.platform.lab.local" deleted
verify: the unbounded CRD is rejected for blowing the estimated cost budget, while adding maxItems and maxLength gets the identical CEL rule accepted. Always bound arrays, maps, and strings before iterating over them in CEL.

Mentioning oldSelf turns a CEL check into a transition rule, which Kubernetes skips on create because there's no previous object to compare against. That asymmetry is both the feature and the gotcha.

kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata: { name: tenantbuckets.platform.lab.local }
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket, shortNames: [tb] }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      subresources: { status: {} }
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: [tier]
              properties:
                tier:   { type: string, enum: [bronze, silver, gold] }
                sizeGB: { type: integer, minimum: 1, maximum: 500, default: 10 }
            status:
              type: object
              properties:
                phase: { type: string }
EOF
kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local --timeout=60s
kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/x-kubernetes-validations","value":[{"rule":"self.tier == oldSelf.tier","message":"tier is immutable once set"}]}]'
sleep 5
kubectl patch tenantbucket good --type merge -p '{"spec":{"tier":"gold"}}'
kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: fresh, namespace: default }
spec: { tier: gold, sizeGB: 20 }
EOF
kubectl get tb
kubectl delete tb fresh
outputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata: { name: tenantbuckets.platform.lab.local }
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket, shortNames: [tb] }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      subresources: { status: {} }
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: [tier]
              properties:
                tier:   { type: string, enum: [bronze, silver, gold] }
                sizeGB: { type: integer, minimum: 1, maximum: 500, default: 10 }
            status:
              type: object
              properties:
                phase: { type: string }
EOF
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local created
$ kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local --timeout=60s
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local condition met
$ kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
tenantbucket.platform.lab.local/good created
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/x-kubernetes-validations","value":[{"rule":"self.tier == oldSelf.tier","message":"tier is immutable once set"}]}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ sleep 5
$ kubectl patch tenantbucket good --type merge -p '{"spec":{"tier":"gold"}}'
The TenantBucket "good" is invalid: spec: Invalid value: tier is immutable once set
$ kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: fresh, namespace: default }
spec: { tier: gold, sizeGB: 20 }
EOF
tenantbucket.platform.lab.local/fresh created
$ kubectl get tb
Warning: short name "tb" could also match lower priority resource triggerbindings.triggers.tekton.dev
NAME    AGE
fresh   0s
good    6s
$ kubectl delete tb fresh
Warning: short name "tb" could also match lower priority resource triggerbindings.triggers.tekton.dev
tenantbucket.platform.lab.local "fresh" deleted from default namespace
verify: changing tier on the existing object is blocked with your custom message, while creating a brand-new object with that same tier goes right through.

Historically, tightening a CRD schema wedged every existing object that violated the new rule, even when you only wanted to add a label. Validation ratcheting lets updates pass whenever the already-invalid field stays unchanged, so you can tighten constraints before cleaning up legacy data.

kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata: { name: tenantbuckets.platform.lab.local }
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket, shortNames: [tb] }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      subresources: { status: {} }
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: [tier]
              properties:
                tier:   { type: string, enum: [bronze, silver, gold] }
                sizeGB: { type: integer, minimum: 1, maximum: 500, default: 10 }
            status:
              type: object
              properties:
                phase: { type: string }
EOF
kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local --timeout=60s
kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: legacy, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/tier/pattern","value":"^gold$"}]'
sleep 5
kubectl label tenantbucket legacy team=a
kubectl patch tenantbucket legacy --type merge -p '{"spec":{"sizeGB":120}}'
kubectl patch tenantbucket legacy --type merge -p '{"spec":{"tier":"silver"}}'
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/tier/pattern"}]'
kubectl delete tb legacy
outputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata: { name: tenantbuckets.platform.lab.local }
spec:
  group: platform.lab.local
  scope: Namespaced
  names: { plural: tenantbuckets, singular: tenantbucket, kind: TenantBucket, shortNames: [tb] }
  versions:
    - name: v1alpha1
      served: true
      storage: true
      subresources: { status: {} }
      schema:
        openAPIV3Schema:
          type: object
          properties:
            spec:
              type: object
              required: [tier]
              properties:
                tier:   { type: string, enum: [bronze, silver, gold] }
                sizeGB: { type: integer, minimum: 1, maximum: 500, default: 10 }
            status:
              type: object
              properties:
                phase: { type: string }
EOF
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local configured
$ kubectl wait --for=condition=Established crd/tenantbuckets.platform.lab.local --timeout=60s
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local condition met
$ kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: good, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
tenantbucket.platform.lab.local/good unchanged
$ kubectl apply -f - <<'EOF'
apiVersion: platform.lab.local/v1alpha1
kind: TenantBucket
metadata: { name: legacy, namespace: default }
spec: { tier: silver, sizeGB: 100 }
EOF
tenantbucket.platform.lab.local/legacy created
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/tier/pattern","value":"^gold$"}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ sleep 5
$ kubectl label tenantbucket legacy team=a
tenantbucket.platform.lab.local/legacy labeled
$ kubectl patch tenantbucket legacy --type merge -p '{"spec":{"sizeGB":120}}'
tenantbucket.platform.lab.local/legacy patched
$ kubectl patch tenantbucket legacy --type merge -p '{"spec":{"tier":"silver"}}'
tenantbucket.platform.lab.local/legacy patched (no change)
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0/schema/openAPIV3Schema/properties/spec/properties/tier/pattern"}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ kubectl delete tb legacy
Warning: short name "tb" could also match lower priority resource triggerbindings.triggers.tekton.dev
tenantbucket.platform.lab.local "legacy" deleted from default namespace
verify: labeling legacy and changing its sizeGB both succeed even though tier: silver violates the new ^gold$ pattern, and an unchanged patch is a no-op (whereas changing tier to another non-matching value like bronze would be rejected).

kubectl get --field-selector works out of the box on built-in kinds, but fails on your CRD until you explicitly declare which fields are selectable. It's a one-line schema addition, and the refusal error beforehand is unmistakable.

kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=silver
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/selectableFields","value":[{"jsonPath":".spec.tier"}]}]'
sleep 5
kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=silver
kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=gold
outputcaptured 2026-09-12
$ kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=silver
Error from server (BadRequest): Unable to find "platform.lab.local/v1alpha1, Resource=tenantbuckets" that match label selector "", field selector "spec.tier=silver": field label not supported: spec.tier
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/0/selectableFields","value":[{"jsonPath":".spec.tier"}]}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ sleep 5
$ kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=silver
NAME   AGE
good   4h48m
$ kubectl get tenantbuckets.platform.lab.local --field-selector spec.tier=gold
No resources found in default namespace.
verify: the first query fails with field label not supported: spec.tier, and right after patching selectableFields the exact same query filters cleanly. Because filtering happens server-side, it matters hugely once you have ten thousand CRs instead of ten.

status.storedVersions records every schema version that might still have bytes sitting in etcd. Kubernetes won't let you drop a version while it's in that list: you have to rewrite every existing object through the new storage version and then update status.

kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.storedVersions}{"\n"}'
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/-","value":{"name":"v1beta1","served":true,"storage":false,"subresources":{"status":{}},"schema":{"openAPIV3Schema":{"type":"object","properties":{"spec":{"type":"object","properties":{"tier":{"type":"string"},"sizeGB":{"type":"integer"}}},"status":{"type":"object","properties":{"phase":{"type":"string"}}}}}}}}]'
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"replace","path":"/spec/versions/0/storage","value":false},{"op":"replace","path":"/spec/versions/1/storage","value":true}]'
kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.storedVersions}{"\n"}'
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0"}]'
kubectl get tb -o name | xargs -r -I{} kubectl patch {} --type merge -p '{"metadata":{"annotations":{"rewrite":"now"}}}'
kubectl patch crd tenantbuckets.platform.lab.local --subresource status --type merge -p '{"status":{"storedVersions":["v1beta1"]}}'
kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0"}]'
kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{range .spec.versions[*]}{.name} storage={.storage}{"\n"}{end}'
outputcaptured 2026-09-12
$ kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.storedVersions}{"\n"}'
["v1alpha1"]
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"add","path":"/spec/versions/-","value":{"name":"v1beta1","served":true,"storage":false,"subresources":{"status":{}},"schema":{"openAPIV3Schema":{"type":"object","properties":{"spec":{"type":"object","properties":{"tier":{"type":"string"},"sizeGB":{"type":"integer"}}},"status":{"type":"object","properties":{"phase":{"type":"string"}}}}}}}}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"replace","path":"/spec/versions/0/storage","value":false},{"op":"replace","path":"/spec/versions/1/storage","value":true}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.storedVersions}{"\n"}'
["v1alpha1","v1beta1"]
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0"}]'
The CustomResourceDefinition "tenantbuckets.platform.lab.local" is invalid: status.storedVersions[0]: Invalid value: "v1alpha1": missing from spec.versions; v1alpha1 was previously a storage version, and must remain in spec.versions until a storage migration ensures no data remains persisted in v1alpha1 and removes v1alpha1 from status.storedVersions
$ kubectl get tb -o name | xargs -r -I{} kubectl patch {} --type merge -p '{"metadata":{"annotations":{"rewrite":"now"}}}'
Warning: short name "tb" could also match lower priority resource triggerbindings.triggers.tekton.dev
tenantbucket.platform.lab.local/good patched
$ kubectl patch crd tenantbuckets.platform.lab.local --subresource status --type merge -p '{"status":{"storedVersions":["v1beta1"]}}'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ kubectl patch crd tenantbuckets.platform.lab.local --type json -p '[{"op":"remove","path":"/spec/versions/0"}]'
customresourcedefinition.apiextensions.k8s.io/tenantbuckets.platform.lab.local patched
$ kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{range .spec.versions[*]}{.name} storage={.storage}{"\n"}{end}'
v1beta1 storage=true
verify: the first attempt to remove v1alpha1 is blocked citing status.storedVersions; once you rewrite every object under v1beta1 and patch storedVersions, removal succeeds. That no-op rewrite loop is the real migration step; be ready to explain why a conversion webhook alone doesn't eliminate it.

Before chasing why a custom resource "doesn't work", verify that the API server actually accepted the CRD. Two status conditions tell you immediately, and they should be your first stop on any unfamiliar CRD.

kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.conditions[*].type}{"\n"}'
kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason, message}'
kubectl get crd appenvironments.platform.lab.local -o jsonpath='{.status.conditions[*].type}{"\n"}'
outputcaptured 2026-09-12
$ kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.conditions[*].type}{"\n"}'
NamesAccepted Established
$ kubectl get crd tenantbuckets.platform.lab.local -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason, message}'
{
  "type": "NamesAccepted",
  "status": "True",
  "reason": "NoConflicts",
  "message": "no conflicts found"
}
{
  "type": "Established",
  "status": "True",
  "reason": "InitialNamesAccepted",
  "message": "the initial names have been accepted"
}
$ kubectl get crd appenvironments.platform.lab.local -o jsonpath='{.status.conditions[*].type}{"\n"}'
NamesAccepted Established
verify: both CRDs show NamesAccepted and Established as True. Be ready to explain what it means if NamesAccepted is True while Established is False (or missing), and what a False NamesAccepted usually signals on a busy cluster.

Self-check

answer before opening
A user says their field "does not work". kubectl get -o yaml shows it missing entirely, and no error was printed. What happened?

Schema pruning. The field isn't declared in the CRD's OpenAPI schema, so the API server stripped it on write, and whatever applied it bypassed strict field validation (a controller, a GitOps sync, or --validate=false), which is why nothing errored. Fix it by adding the field to the schema (or, in rare cases, adding x-kubernetes-preserve-unknown-fields on that subtree). Declaring it properly gives users real validation and docs.

Your controller's status writes vanish. One likely cause?

The status subresource is enabled, and the writer is hitting the main resource endpoint, which silently ignores the status stanza. Switch to UpdateStatus() (or kubectl patch --subresource=status). And watch out for the flip side: with no status subresource at all, any spec write from a user overwrites the status your controller just wrote.

You must forbid changing spec.tier after creation. How, without a webhook?

Add a CEL transition rule right on the field using x-kubernetes-validations: rule: "self == oldSelf" with a clear message like "tier is immutable". Because the API server evaluates CEL against the stored object on updates, you get immutability with zero webhooks to operate.

You want to serve v1alpha1 and v1beta1 with different fields. What do you need?

Mark both versions served: true, mark exactly one storage: true, and set up a conversion strategy: None only works when fields are compatible, so diverging fields need a conversion Webhook. Everything stays persisted in the storage version in etcd and gets converted on the fly when served.

What does a CRD give you for free, and what does it definitively not give you?

For free: etcd persistence, OpenAPI and CEL validation, defaulting, RBAC integration, watches and informers, kubectl support and explain docs, ResourceQuota counting, and admission/policy visibility. Definitely not free: behavior. Nothing actually happens until a controller reconciles the object.

Your CEL rule over a list of strings is rejected with "exceeded budget by more than 100x". What do you change?

Bound the inputs your rule loops over: add maxItems on the array and maxLength on its string items (or maxProperties on a map). The static cost estimator assumes worst-case sizes for unbounded collections, so adding bounds lets the exact same CEL expression pass, and gives your API cleaner input limits too.

You tightened a pattern on spec.name. Existing objects with old-style names must still be updatable. What makes that work, and what does it not cover?

Validation ratcheting (GA since 1.33): updates succeed as long as every part failing the new schema stays unchanged. It doesn't cover transition rules (oldSelf), list-type changes, new required fields, renamed properties, metadata rules, or create requests. For custom grandfathering rules, use optionalOldSelf: true inside a CEL rule.

You want to drop v1alpha1 from a CRD but the update is refused. Why, and what is the sequence?

status.storedVersions still includes v1alpha1, so etcd might still hold objects serialized in that version and Kubernetes refuses to strand them. Set v1 as the storage version (optionally setting served: false on v1alpha1 first), rewrite every object via a StorageVersionMigration or a no-op update loop so etcd re-persists them as v1, patch status.storedVersions to ["v1"], and then remove v1alpha1 from spec.versions.

Enable kubectl get widgets --field-selector spec.tier=gold. Field, version status, and limits?

Add spec.versions[].selectableFields: [{jsonPath: .spec.tier}] (GA since Kubernetes 1.32). You're limited to scalar fields, at most 8 per version, and clients have to query a version that declares them. It eliminates the old workaround of duplicating spec fields into labels just to filter efficiently.

Docs to know your way around

study time, not exam time
  • kubernetes.io: "Extend the Kubernetes API with CustomResourceDefinitions" (one long page covering versions, pruning, CEL validation and defaults), and "Versions in CustomResourceDefinitions".
  • Offline: kubectl explain crd.spec.versions --recursive when you forget field placement, which everyone does; kubectl get crd <name> -o yaml to learn from an operator's own schema.
  • kubernetes.io: "Extend the Kubernetes API with CustomResourceDefinitions", sections Specifying a structural schema, Validation rules (messageExpression, reason, fieldPath, transition rules, resource use), Validation ratcheting, Defaulting and Nullable, Field selectors: the versions and error texts above come from there.
  • kubernetes.io: "Versions in CustomResourceDefinitions": version priority sorting, conversion strategies, storedVersions and the storage version migration procedure.
  • Offline: kubectl explain crd.spec.versions.schema.openAPIV3Schema --recursive lists every x-kubernetes-* extension the server understands; kubectl get crd <name> -o jsonpath='{.status}' for Established, NamesAccepted, NonStructural and storedVersions.