Custom Resource Definitions (CRDs) are one of the advanced features of Kubernetes that enable the platform to be extended beyond the built-in resources. They allow developers to create their own custom resources and manage them using Kubernetes’ declarative API.
CRDs essentially define a new object kind, which can be treated as a first-class Kubernetes object in the same way as Pods, Deployments, and Services. They can be used to create a higher-level abstraction on top of the built-in resources or to introduce new resource types that are specific to an application or domain.
To create a CRD, you need to define a new API resource in Kubernetes. This can be done using a YAML or JSON file that specifies the resource’s schema, behavior, and metadata. Here is an example YAML file that defines a CRD for a custom resource named MyResource:
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: myresources.example.com
spec:
group: example.com
version: v1
scope: Namespaced
names:
plural: myresources
singular: myresource
kind: MyResource
shortNames:
- mr
validation:
openAPIV3Schema:
type: object
properties:
name:
type: string
value:
type: integer
required:
- name
- value
In this example, the CustomResourceDefinition object defines a new API resource named MyResource, which belongs to the example.com group and the v1 version. The scope field specifies that this resource is namespaced, meaning it can only be used within a specific namespace. The names field specifies the plural and singular names of the resource, as well as a shorthand name. The validation field specifies the schema for the resource’s data, which in this case includes a required name field and an optional value field.
Once the CRD is defined, you can use it to create instances of the custom resource using the Kubernetes API. For example, here is a YAML file that creates an instance of the MyResource custom resource:
apiVersion: example.com/v1
kind: MyResource
metadata:
name: my-resource-1
spec:
name: example
value: 42
This YAML file creates a new instance of the MyResource custom resource with the name my-resource-1, and sets the name field to "example" and the value field to 42.
CRDs are powerful because they allow developers to create custom resources that can be managed using the same Kubernetes tools and APIs as the built-in resources. This makes it easy to integrate custom resources with other Kubernetes objects and to automate management tasks using tools like Kubernetes Operators. CRDs also enable better observability and automation by defining the desired state of an application or system as a declarative resource, which can be version-controlled and audited.