Skip to content
LF Cert Trainer

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

1/12Custom Resource Definitions
0:00 / 4:26

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.

WordWhat it isExample
CustomResourceDefinition (CRD)The definition of a new kind. Cluster-wide, one per kindbackups.training.example.com
Custom resource (CR)One object of that kindA Backup named nightly in namespace default
ControllerA program that watches custom resources and acts on themThe subject of the next lesson
A CRD adds a new type to the APIwriteapplynow servesacceptsstoredYoukubectl applyCRDkind: BackupAPI serverlearns the new kindNew API path.../v1/backupsBackup nightlya custom resourceetcdstores the object
A CRD adds a new type to the API. Applying a CRD does not start anything. It tells the API server to serve one more path. From then on, objects of the new kind are accepted and stored in etcd like any built-in object.

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
FieldRule to remember
metadata.nameExactly <plural>.<group>. Anything else is rejected
spec.groupA DNS-style name you control. It cannot be changed later
spec.scopeNamespaced or Cluster. It cannot be changed later
spec.names.kindCamelCase, singular. This is what users put after kind:
spec.names.pluralLower case. This is what appears in the URL and in RBAC rules
spec.versions[*].servedfalse switches a version off without removing it
spec.versions[*].storageExactly one version must have true
spec.versions[*].schemaRequired 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.

What happens to a custom resource you applysendcheckinvalidvalidwatchkubectl applykind: BackupAPI serverlogin and RBACCRD schemavalidate, defaultRejectederror names the fieldetcdobject is storedControllernone yet: next lesson
What happens to a custom resource you apply. The API server checks who you are, then checks the object against the schema in the CRD. A valid object is stored. Nothing acts on it until a controller watches for it.

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, pattern and 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 default is filled in when the user leaves it out. In the CRD above a Backup without retentionDays is stored with retentionDays: 7.

  • Pruning. Fields that the schema does not describe are not stored. Current kubectl checks 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=false the 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.

Served versions and the storage versionv1v2save404Clientasks for v1Clientasks for v2API serverserves v1 and v2etcdstored as v2v1alpha1served: false
Served versions and the storage version. A CRD can list several versions. Each one is switched on or off with served. Exactly one has storage set to true, and every object is written to etcd in that version, whichever version the client used.

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: true means clients may read and write that version. served: false makes 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 apiVersion field, 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

BlockWhat it adds
subresources.statusA separate /status endpoint. Users write spec, the controller writes status, and each can get its own RBAC rule
subresources.scaleMakes kubectl scale and the HorizontalPodAutoscaler work on the custom kind
additionalPrinterColumnsExtra columns in kubectl get. Without it you see only NAME and AGE
names.shortNamesAbbreviations such as bk
names.categoriesGroups such as all, so the kind appears in kubectl get all
selectableFieldsLets --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.name wrong. It must be <plural>.<group>: backups.training.example.com, not backup and not Backup.
  • Mixing up the two apiVersion values. The CRD itself is apiextensions.k8s.io/v1. A custom resource uses the CRD's own group and version, such as training.example.com/v1.
  • Leaving out the schema. In apiextensions.k8s.io/v1 every version needs schema.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 for Established.
  • Deleting a CRD to "clean up". kubectl delete crd removes 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 Namespaced kind live in namespaces.

Recap

  • A CRD is an object of kind CustomResourceDefinition in apiextensions.k8s.io/v1 that adds a new kind to the API at run time. Objects of that kind are custom resources.
  • Its name is <plural>.<group>. Users write apiVersion: <group>/<version> and kind: <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 has storage: true.
  • Find and read CRDs with kubectl get crd, kubectl api-resources --api-group=, and kubectl 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.