Custom resource definitions
Adding your own API types to Kubernetes: a CRD's schema, defaults, CEL validation rules, immutability, printer columns, the status subresource, and versioning.
The Kubernetes API and object modelControllers and the reconcile loopAdmission control and policy
Custom resource definitions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A CRD registers a new resource type with the API server: same REST paths, kubectl, RBAC, watch, audit and storage in etcd as built-in kinds. It stores data only. Behaviour comes from a controller.
- The structural OpenAPI v3 schema validates types, enums, patterns and ranges, applies defaults, and prunes unknown fields, all inside the API server before the object is stored.
- x-kubernetes-validations runs CEL rules for cross-field checks, and transition rules using oldSelf, such as making a field immutable, without any webhook.
- With the status subresource, writes to the main resource ignore status, and writes to /status ignore spec. That separates what users ask for from what the controller reports.
- additionalPrinterColumns shape kubectl get output, shortNames and categories make the type feel native, and scale exposes a replica count to kubectl scale and the HPA.
- Versions evolve with served and storage flags. Only one version is stored, and changing schemas across versions needs a conversion webhook unless the shapes are identical.
Your platform has nouns Kubernetes doesn’t
A platform team offers developers a database. Today that means a ticket, or a Terraform module, or a wiki page of instructions. Kubernetes already has a good way to ask for things: write a declarative object, apply it, let a controller make it real, read its status. It just doesn’t have a Database kind.
A CustomResourceDefinition (CRD) adds one. Every tool from earlier lessons then works on it unchanged: kubectl get, RBAC, watches, server-side apply, audit logs, GitOps. You’ve already met CRDs in this roadmap: Karpenter’s NodePools, Argo CD’s Applications, Argo Rollouts’ Rollouts.
A CRD, piece by piece
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: databases.platform.example.com
spec:
group: platform.example.com
scope: Namespaced
names:
plural: databases
singular: database
kind: Database
shortNames: [db]
versions:
- name: v1alpha1
served: true
storage: true
subresources:
status: {}
additionalPrinterColumns:
- {name: Engine, type: string, jsonPath: .spec.engine}
- {name: Size, type: string, jsonPath: .spec.storage}
- {name: Phase, type: string, jsonPath: .status.phase}
- {name: Age, type: date, jsonPath: .metadata.creationTimestamp}
schema:
openAPIV3Schema:
type: object
required: [spec]
properties:
spec:
type: object
required: [engine, storage]
x-kubernetes-validations:
- rule: "self.engine != 'mysql' || self.version.startsWith('8.')"
message: "only MySQL 8.x is supported"
properties:
engine:
type: string
enum: [postgres, mysql]
x-kubernetes-validations:
- rule: "self == oldSelf"
message: "engine is immutable"
version: {type: string, default: "17"}
storage: {type: string, pattern: '^[0-9]+Gi$'}
replicas: {type: integer, minimum: 1, maximum: 5, default: 1}
status:
type: object
properties:
phase: {type: string}
The name must be <plural>.<group>. Once the CRD’s Established condition is true, the API server serves /apis/platform.example.com/v1alpha1/namespaces/*/databases, and discovery tells kubectl about it.
Schema, defaults and pruning
I applied the CRD to a lab API server, then a minimal object:
apiVersion: platform.example.com/v1alpha1
kind: Database
metadata: {name: orders, namespace: shop}
spec:
engine: postgres
storage: 20Gi
Reading it back showed the server-side defaults: {"engine":"postgres","replicas":1,"storage":"20Gi","version":"17"}. Defaults are applied on create and on every read from etcd, so adding a default later fills it in for old objects too.
A bad object collected every violation in one response:
The Database "bad" is invalid:
* spec.storage: Invalid value: "20GB": spec.storage in body should match '^[0-9]+Gi$'
* spec.replicas: Invalid value: 9: spec.replicas in body should be less than or equal to 5
* spec: Invalid value: only MySQL 8.x is supported
The schema must be structural: every field typed, no ambiguous unions. Fields not in the schema are pruned, silently dropped, unless marked x-kubernetes-preserve-unknown-fields. That’s what lets defaulting, validation and field ownership work predictably.
CEL validation rules
The third error came from a CEL rule, self.engine != 'mysql' || self.version.startsWith('8.'), a cross-field check plain OpenAPI can’t express. Rules attach at any level of the schema, and self is the value at that level.
Rules that mention oldSelf are transition rules, evaluated on updates with the previous value. The engine field’s rule made it immutable:
$ kubectl -n shop patch db orders --type=merge -p '{"spec":{"engine":"mysql","version":"8.4"}}'
The Database "orders" is invalid: spec.engine: Invalid value: "mysql": engine is immutable
Before CEL (GA in 1.29), all of this needed a validating webhook: another service to deploy, secure and keep available, as the admission lesson showed. The API server estimates each rule’s cost when the CRD is created and rejects rules that could be too expensive. Bound list sizes with maxItems and string lengths with maxLength so the estimates stay low. Ratcheting (GA since 1.33) lets an update through if it doesn’t touch an already-invalid field, so tightening a schema doesn’t block unrelated edits to old objects.
The status subresource
With subresources.status enabled, spec and status have separate write paths:
$ kubectl -n shop patch db orders --type=merge -p '{"status":{"phase":"Ready"}}'
database.platform.example.com/orders patched (no change)
$ kubectl -n shop patch db orders --subresource=status --type=merge -p '{"status":{"phase":"Ready"}}'
database.platform.example.com/orders patched
$ kubectl -n shop get db
NAME ENGINE SIZE PHASE AGE
orders postgres 20Gi Ready 0s
The first patch was ignored, since writes to the main resource discard status changes. Only the /status write took. Users own spec, the controller owns status, and RBAC can grant them separately (databases versus databases/status). metadata.generation also only increments on spec changes, so a controller can report observedGeneration to say which spec it has acted on. The Engine, Size and Phase columns came from additionalPrinterColumns.
A scale subresource maps a spec field and a status field to the standard Scale API, so kubectl scale and the HPA work on the custom kind.
Versions
APIs change. A CRD can list several versions. Each is served or not, and exactly one is the storage version that objects are written in. If the schemas differ in shape, say storage: 20Gi becoming storage: {size: 20Gi, class: fast}, the API server needs a conversion webhook to translate between them on every read and write. With strategy: None, it only changes apiVersion. Plan the API before v1, because removing a version requires migrating every stored object to a newer one first (storedVersions in the CRD status tracks which versions still exist in etcd).
When a CRD is the wrong tool
- Configuration only one app reads: use a ConfigMap.
- Data that changes many times a second or is large: etcd isn’t a database for application data.
- Something already modelled: prefer built-in kinds and their ecosystem.
About the video
The embed is Chirag Kyal’s KCD Hyderabad 2024 talk “CRD Validation in Kubernetes”, 23 minutes. Its description says it covers why webhook-based validation is painful (binary bundles, multi-version CRDs), introduces CEL, and live-demos multi-field validation and immutability checks, the same mechanisms run above. It has no chapter list, and I judged it from the description only, since transcripts couldn’t be fetched. English was judged from the title, description and English caption track. The page shows no audio-language flag. It’s a small community channel, so the owner should check the audio. VarJosh’s CKA episode in deeper is a broader introduction to custom resources.
What was run: the CRD, the defaults, the three validation errors, the immutability rejection, both status patches and the printer columns are real output from a local Kubernetes v1.37.3 API server whose nodes run no containers. Conversion webhooks, cost estimation and ratcheting weren’t exercised. They are from the CRD and CEL docs, checked 2026-11-29.
Where this fits
The Database object is accepted and does nothing. Next, the code that makes it real: operators and writing a controller.
Check yourself
You create a CRD and a Database object, but no database appears anywhere. Why?
A CRD only teaches the API server to store and validate Database objects. Something has to watch them and act, which is a controller or operator. Without one, the object is just data in etcd.
A user sets status.phase: Ready in a kubectl apply of their Database. What happens if the CRD has the status subresource enabled?
The status change is ignored. With the subresource on, writes to the main resource reset status, and only writes to /status (normally by the controller) can change it.
How do you make spec.engine unchangeable after creation without writing a webhook?
Add an x-kubernetes-validations rule on the field: self == oldSelf. Transition rules run on updates with access to the previous value, and the API server rejects changes with your message.
Why does Kubernetes require structural schemas and prune unknown fields?
So every stored object has a known shape. Typos and fields from newer clients are dropped instead of being stored silently, defaults and validation are well-defined, and server-side apply can track field ownership.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.