Custom Resource Definition (CRD)

Custom Resource Definition (CRD)

We can define custom K8s resources (objects) using CRDs.
Let’s consider an example of creating a FlightTicket object using the definition file below. Creating a resource using the definition file below will throw an error as FlightTicket object is not yet defined in K8s. We first need to create a CRD for it.
apiVersion: flights.com/v1 kind: FlightTicket metadata: name: my-flight-ticket spec: from: Mumbai to: London count: 2
The CRD to create FlightTicket object in K8s:
apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: flighttickets.flights.com spec: scope: Namespaced group: flights.com names: kind: FlightTicket singular: flightticket plural: flighttickets shortNames: - ft versions: - name: v1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: from: type: string to: type: string count: type: integer minimum: 1 maximum: 10
  • scope: Namespaced signifies that this resource will be scoped within the Namespace and not the whole cluster. Custom resources can also be cluster scoped.
  • group: flights.com refers to the API group in which the custom resource will be created
  • names configures the kind of the resource, its singular, plural and short names.
  • versions specifies the supported API versions for the resource. served: true signifies that the version is being served through the kube-apiserver. Only one of the versions can be the storage version and have storage: true.
  • schema defines the the properties to expect in the spec section of the resource. For integer fields we can specify validations such as minimum, maximum etc.
  • Note that schema is defined under the version.
 

Custom
Controllers
Controllers

Creating a customer resource in K8s such as FlightTicket doesn’t do much. It’s just a configuration saved in the etcd store. To actually book a flight ticket when a FlightTicket object is created, we need to write a custom controller which will continuously monitor the FlightTicket objects in the etcd store and make API calls to a flight booking service.