Lesson 90 · Section 7: Security
Lesson 90: Custom Resource Definitions: teaching the API a new kind
What a CRD is, what the API server does when you apply one, how the schema validates, defaults and prunes custom resources, and the commands to find, read and troubleshoot the CRDs that operators install. · 18 min read · 4 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
What a Custom Resource Definition is
Everything you have used so far, Pods, Deployments, Services, ConfigMaps, is a resource: a kind of object that the API server knows how to accept, check, store and list. The list of built-in resources is fixed in each Kubernetes release.
A CustomResourceDefinition (CRD) adds a resource to that list while the cluster is running. It is itself an ordinary object: you write a manifest that describes a new kind (its name, its API group, its versions and its fields), apply it, and a few seconds later the API server serves that kind. The objects you then create of the new kind are called custom resources.
| Word | What it is | Example |
|---|---|---|
| CustomResourceDefinition (CRD) | The definition of a new kind. Cluster-wide, one per kind | backups.training.example.com |
| Custom resource (CR) | One object of that kind | A Backup named nightly in namespace default |
| Controller | A program that watches custom resources and acts on them | The subject of the next lesson |
Parts:
- You (kubectl apply)
- CRD (kind: Backup)
- API server (learns the new kind)
- New API path (.../v1/backups)
- Backup nightly (a custom resource)
- etcd (stores the object)
Connections:
- You to CRD: write
- CRD to API server: apply
- API server to New API path: now serves
- New API path to Backup nightly: accepts
- Backup nightly to etcd: stored
Why it exists
Kubernetes is extended by add-ons far more often than it is changed. cert-manager needs a Certificate, the
Gateway API needs a Gateway and an HTTPRoute, Calico needs an IPPool, a database operator needs something
like a Cluster. If each of these required a change to Kubernetes itself, none of them would exist.
CRDs let every add-on bring its own kinds and still feel native. Its objects are created with kubectl apply,
listed with kubectl get, protected by RBAC, kept in etcd, and included in etcd backups. As an administrator you
will rarely design a CRD, but you will install, inspect and troubleshoot them constantly, and the CKA curriculum
names them directly: "Understand CRDs, install and configure operators".
How it works
The API server grows a new path
Every resource lives at a path in the API. Built-in Deployments are at /apis/apps/v1/namespaces/<ns>/deployments.
When you apply a CRD, the API server (more precisely the extension server built into kube-apiserver) reads it and
starts to serve one more path of the same shape:
/apis/<group>/<version>/namespaces/<namespace>/<plural>
/apis/training.example.com/v1/namespaces/default/backups
No component is restarted and no node is touched. The CRD reports that it is ready through a condition called
Established, usually within a second or two:
kubectl wait --for condition=established --timeout=30s crd/backups.training.example.com
That wait matters in scripts. A custom resource applied in the same breath as its CRD can arrive before the new
path is served and fail with no matches for kind.
Reading a CRD, block by block
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: backups.training.example.com # must be <plural>.<group>
spec:
group: training.example.com # first half of the apiVersion users write
scope: Namespaced # or Cluster
names:
plural: backups # used in the URL and in "kubectl get backups"
singular: backup
kind: Backup # used in manifests: "kind: Backup"
shortNames: [bk]
versions:
- name: v1 # second half of the apiVersion
served: true # clients may use this version
storage: true # objects are written to etcd in this version
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: [schedule, target]
properties:
schedule:
type: string
target:
type: string
retentionDays:
type: integer
minimum: 1
default: 7
| Field | Rule to remember |
|---|---|
metadata.name | Exactly <plural>.<group>. Anything else is rejected |
spec.group | A DNS-style name you control. It cannot be changed later |
spec.scope | Namespaced or Cluster. It cannot be changed later |
spec.names.kind | CamelCase, singular. This is what users put after kind: |
spec.names.plural | Lower case. This is what appears in the URL and in RBAC rules |
spec.versions[*].served | false switches a version off without removing it |
spec.versions[*].storage | Exactly one version must have true |
spec.versions[*].schema | Required in apiextensions.k8s.io/v1. Describes the fields |
The CRD itself is always cluster-scoped, even when the kind it defines is namespaced. There is no
kubectl -n for kubectl get crd.
The schema: validate, default, prune
The openAPIV3Schema block is what turns "any YAML at all" into a real API. The API server applies it to every
create and update of a custom resource.
Parts:
- kubectl apply (kind: Backup)
- API server (login and RBAC)
- CRD schema (validate, default)
- Rejected (error names the field)
- etcd (object is stored)
- Controller (none yet: next lesson)
Connections:
- kubectl apply to API server: send
- API server to CRD schema: check
- CRD schema to Rejected: invalid
- CRD schema to etcd: valid
- etcd to Controller: watch
-
Validation. Types,
required,enum,minimum,maximum,patternand similar rules are enforced. A violation is refused with an error that names the field:The Backup "nightly" is invalid: spec.retentionDays: Invalid value: 0: spec.retentionDays in body should be greater than or equal to 1 -
Defaulting. A field with
defaultis filled in when the user leaves it out. In the CRD above a Backup withoutretentionDaysis stored withretentionDays: 7. -
Pruning. Fields that the schema does not describe are not stored. Current
kubectlchecks strictly, so a misspelt field is usually refused before it is pruned:Error from server (BadRequest): error when creating "nightly.yaml": Backup in version "v1" cannot be handled as a Backup: strict decoding error: unknown field "spec.retention"With
--validate=falsethe same object is accepted and the unknown field silently disappears.
Rules that compare fields with each other ("minReplicas must not exceed replicas") are written in the
Common Expression Language under x-kubernetes-validations. You only need to recognise that block when you see it.
A custom resource is only data
This split is the same one the built-in kinds use. A Deployment is also only a record in etcd; the Deployment
controller inside kube-controller-manager is what creates ReplicaSets from it. For custom kinds the controller is
not part of Kubernetes, so somebody has to install it. Custom controllers and operators are the next two lessons.
Versions: served and storage
A kind usually evolves: v1alpha1, then v1beta1, then v1. A CRD lists all of them under spec.versions.
Parts:
- Client (asks for v1)
- Client (asks for v2)
- API server (serves v1 and v2)
- etcd (stored as v2)
- v1alpha1 (served: false)
Connections:
- Client to API server: v1
- Client to API server: v2
- API server to etcd: save
- API server to v1alpha1: 404
served: truemeans clients may read and write that version.served: falsemakes requests for it fail with 404, although the CRD still lists the version.- Exactly one version has
storage: true. Every object is written to etcd in that version, whichever version the client sent. - When versions differ in shape, the CRD names a conversion webhook that translates between them. Without one, the
API server only rewrites the
apiVersionfield, which is enough when the fields are the same.
For the exam, the useful skill is reading these fields from an installed CRD:
kubectl get crd backups.training.example.com \
-o jsonpath='{range .spec.versions[*]}{.name}{"\t"}served={.served}{"\t"}storage={.storage}{"\n"}{end}'
Optional extras you will meet in real CRDs
| Block | What it adds |
|---|---|
subresources.status | A separate /status endpoint. Users write spec, the controller writes status, and each can get its own RBAC rule |
subresources.scale | Makes kubectl scale and the HorizontalPodAutoscaler work on the custom kind |
additionalPrinterColumns | Extra columns in kubectl get. Without it you see only NAME and AGE |
names.shortNames | Abbreviations such as bk |
names.categories | Groups such as all, so the kind appears in kubectl get all |
selectableFields | Lets --field-selector filter on chosen fields of the custom kind |
Under the hood · Where custom resources live in etcd, and what a backup contains
Custom resources are stored in the same etcd as everything else, under a key built from the group and the plural:
/registry/training.example.com/backups/default/nightly
Two consequences follow. An etcd snapshot contains every CRD and every custom resource, so a restore brings them back together. And unlike built-in kinds, which are stored in a compact binary format, custom resources are stored as JSON, so large or very numerous custom resources cost more etcd space than you might expect.
Under the hood · CRDs are not the only way to extend the API
The other mechanism is API aggregation: you run your own API server and register it with an APIService
object, and kube-apiserver forwards requests for that group to it. metrics-server works this way, which is why
kubectl top depends on an APIService being available.
Aggregation allows things a CRD cannot do, such as custom storage or extra subresources like logs and exec. It
also means writing and operating a server. A CRD needs no code at all, which is why almost every add-on uses CRDs.
kubectl get apiservices shows both: a CRD's group appears there with Local in the SERVICE column.
Using it
Example · Define a kind and create an object of it
Save the CRD from this lesson as backup-crd.yaml, apply it, and wait until it is served:
kubectl apply -f backup-crd.yaml
kubectl wait --for condition=established crd/backups.training.example.com
kubectl api-resources --api-group=training.example.com
NAME SHORTNAMES APIVERSION NAMESPACED KIND
backups bk training.example.com/v1 true Backup
Now write a custom resource. apiVersion is the group, a slash, and the version:
apiVersion: training.example.com/v1
kind: Backup
metadata:
name: nightly
spec:
schedule: "0 2 * * *"
target: postgres-main
kubectl apply -f nightly.yaml
kubectl get bk
kubectl get backup nightly -o jsonpath='{.spec.retentionDays}{"\n"}' # 7, filled in by the default
The object exists, has a default applied, and nothing is backed up: there is no controller.
Example · Explore the CRDs an add-on installed
A task says: "List the CRDs that belong to cert-manager and save them to a file, then save the documentation of
the subject field of the Certificate kind to another file."
kubectl get crd | grep cert-manager
kubectl get crd -o name | grep cert-manager > /opt/crds.txt
kubectl explain reads the schema of the CRD, so it documents custom kinds exactly as it documents Pods:
kubectl explain certificate.spec.subject > /opt/subject.txt
kubectl explain certificate.spec --recursive | less # the whole field tree
If two groups define the same kind name, be explicit: kubectl explain certificates.cert-manager.io.spec, or
add --api-version=cert-manager.io/v1.
Example · Fix 'no matches for kind'
Applying a manifest fails:
error: resource mapping not found for name: "nightly" namespace: "" from "nightly.yaml":
no matches for kind "Backup" in version "training.example.com/v1beta1"
ensure CRDs are installed first
The API server has no path for that group, version and kind. Check which part is wrong:
kubectl get crd | grep -i backup # is the CRD installed at all?
kubectl api-resources | grep -i backup # which apiVersion and kind does it serve?
kubectl get crd backups.training.example.com -o jsonpath='{.spec.versions[*].name}{"\n"}'
Here the CRD serves only v1, and the manifest asks for v1beta1. Change the manifest to
apiVersion: training.example.com/v1. If the CRD is missing, install it first (it normally ships with the
add-on), and only then apply the custom resource.
Example · Give a user access to a custom kind
Custom resources obey RBAC like any other resource. The rule uses the CRD's group and plural:
kubectl create role backup-editor -n default \
--verb=get,list,watch,create,update,delete \
--resource=backups.training.example.com
kubectl create rolebinding backup-editor -n default --role=backup-editor --user=jane
kubectl auth can-i create backups.training.example.com -n default --as=jane # yes
Managing the definitions themselves is a separate, cluster-wide permission on customresourcedefinitions in the
group apiextensions.k8s.io. Being allowed to create Backups does not allow anyone to create or delete CRDs.
Example · Add columns to kubectl get
By default kubectl get backups shows only NAME and AGE. Add printer columns to the version in the CRD:
additionalPrinterColumns:
- name: Schedule
type: string
jsonPath: .spec.schedule
- name: Keep
type: integer
jsonPath: .spec.retentionDays
- name: Age
type: date
jsonPath: .metadata.creationTimestamp
additionalPrinterColumns sits beside schema, under the entry in versions. After kubectl apply:
NAME SCHEDULE KEEP AGE
nightly 0 2 * * * 7 4m
Once you define your own columns, add Age yourself as shown, or it is no longer displayed.
Tricks
Common mistakes
- Expecting a custom resource to do something. It is stored and validated, not executed. No controller, no action.
- Getting
metadata.namewrong. It must be<plural>.<group>:backups.training.example.com, notbackupand notBackup. - Mixing up the two
apiVersionvalues. The CRD itself isapiextensions.k8s.io/v1. A custom resource uses the CRD's own group and version, such astraining.example.com/v1. - Leaving out the schema. In
apiextensions.k8s.io/v1every version needsschema.openAPIV3Schema. Without it the CRD is rejected. - Marking two versions, or none, as
storage: true. Exactly one version stores. - Applying the custom resource before the CRD is established. The result is
no matches for kind. Apply the CRD first and wait forEstablished. - Deleting a CRD to "clean up".
kubectl delete crdremoves every object of that kind in every namespace, without asking. - Looking for a CRD in a namespace. CRDs are cluster-scoped. Only the objects of a
Namespacedkind live in namespaces.
Recap
- A CRD is an object of kind
CustomResourceDefinitioninapiextensions.k8s.io/v1that adds a new kind to the API at run time. Objects of that kind are custom resources. - Its name is
<plural>.<group>. Users writeapiVersion: <group>/<version>andkind: <Kind>. - The schema validates custom resources, fills in defaults and drops unknown fields. Errors name the field.
- A custom resource is only data in etcd. A controller makes it real; CRD plus controller is an operator.
- Versions are switched with
served; exactly one hasstorage: true. - Find and read CRDs with
kubectl get crd,kubectl api-resources --api-group=, andkubectl explain. - Deleting a CRD deletes every custom resource of that kind.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
A hands-on lab for this lesson. You get goals, not steps: any solution that reaches them passes.
Define a new resource type with a schema that rejects bad input, then create the first object of that type.
Build · Level 2 · standard · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.