What is a Custom Resource Definition?
sobes.tech AI
Answer from AI
Custom Resource Definition (CRD) is a way to extend Kubernetes by adding new object types to the cluster that are not included in the standard distribution. It allows creating and managing your own resources using standard Kubernetes APIs, kubectl, and other tools.
CRDs define a schema for a new resource type. After creating a CRD, you can create instances of that resource, similar to standard objects like Deployment or Service.
Key aspects of CRD:
- API extensibility: CRDs extend the Kubernetes API, allowing you to work with custom objects just like built-in ones.
- Objects as code: Custom resources are described in YAML/JSON manifests, aligning with infrastructure as code principles.
- Consistency: CRDs provide a consistent way to define and manage custom resources in the cluster.
- Use of operators: CRDs are often used in conjunction with Kubernetes Operators, which implement management logic for custom resources. An operator "knows" how to react to creation, update, or deletion of CRD instances, automating task execution.
Example of CRD definition (partial):
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: myservices.stable.example.com // CRD name
spec:
group: stable.example.com // API group
names:
plural: myservices // Plural name
singular: myservice // Singular name
kind: MyService // Object type name (used in `kind:`)
shortNames:
- ms // Short name
scope: Namespaced // Scope: Cluster or Namespaced
versions:
- name: v1 // API version
served: true // Available for serving
storage: true // Used for storage
schema:
openAPIV3Schema: // Data schema for the resource
type: object
properties:
spec:
type: object
properties:
image:
type: string
replicas:
type: integer
minimum: 1
status:
type: object
properties:
availableReplicas:
type: integer
After applying this CRD, you can create objects of kind: MyService.
Example of using CRD:
apiVersion: stable.example.com/v1
kind: MyService
metadata:
name: my-custom-app
spec:
image: my-docker-image:latest
replicas: 3
Difference between CRD and Operator:
| Characteristic | CRD | Operator |
|---|---|---|
| Function | Defines a new resource type | Implements management logic for the resource |
| Resource type | An object in Kubernetes API | An application running in the cluster (Deployment/StatefulSet) |
| Responsibility | Defines data structure | Reacts to resource state changes, automates tasks |
Thus, CRDs provide a way to extend the Kubernetes API, while Operators use CRDs to automate management of custom resources following Kubernetes controller principles.