Custom Resource Definition

Custom Resource Definition is the feature of kubernetes where it allows us to create custom resources which do not exist in kubernetes. Every resource is in kubernetes such as pods, deployments, replicasets etc are backed by their controllers. These controllers are responsible for managing these resources.

For instance, deployment controller is responsible to create and manage pods replicas. These resources get added to the etcd database, but their behavior is controlled by their controllers.

So, creating a custom resource requires two parts:

  1. Register the custom resource to kubernetes using CustomResourceDefinition.
  2. Creating controller to manage that resource.

CustomResourceDefinition

Creating a custom resource requires resource yaml file as shown below.

person-crd.yaml

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
    name: persons.people.com
spec:
    group: people.com
    scope: Namespaced
    names:
        kind: Person
        singular: person
        plural: persons
        shortNames:
            - pp
    versions:
        - name: v1
          served: true
          storage: true
          openAPIV3Schema:
              type: object
              properties:
                  spec:
                      type: object
                      properties:
                          name:
                              type: string
                          age: 
                              type: integer

where

  1. spec.group is api group
  2. spec.scope defines this custom resource is namespaced
  3. spec.names defines the names this resource can be searched with such as k get person or k get persons or using short name k get pp.
  4. spec.versions list all the available versions out of which only one can be storage equal to true refer note. served tells if the version can be used.
  5. spec.versions[].openAPIV3Schema defines the spec structure of custom resource.

Create this custom resource definition using command,

k create -f person-crd.yaml

Creating custom resource

Once the custom resource definition is created using persons-crd.yaml resource file, we can create custom resource of kind Person.

apiVersion: people.com/v1
kind: Person
metadata:
    name: nitin
    namespace: learning
spec:
    name: nitin sharma
    age: 28

It is to be noted that this will only create the resource in the etcd server, and that’s it. There is no controller defined to handle this custom resource.