In this lesson, we will explore Custom Resource Definitions (CRDs) and Operators in Kubernetes. These powerful features allow you to extend Kubernetes' functionality and create custom resources tailored to your application's needs.
Custom Resource Definitions allow you to define your own resource types in Kubernetes. This means you can create resources that are not part of the standard Kubernetes API, enabling you to manage and interact with your application in a way that fits your requirements.
To create a CRD, you need to define the schema of your custom resource. Below is an example of a CRD for a custom resource called MyResource.
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: myresources.mycompany.com
spec:
group: mycompany.com
names:
kind: MyResource
listKind: MyResourceList
plural: myresources
singular: myresource
scope: Namespaced
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
foo:
type: string
bar:
type: integer
To apply the CRD, save the YAML above to a file named myresource-crd.yaml and run:
kubectl apply -f myresource-crd.yaml
Once the CRD is created, you can create an instance of MyResource as follows:
apiVersion: mycompany.com/v1
kind: MyResource
metadata:
name: example-myresource
spec:
foo: "Hello"
bar: 42
Save this to a file named example-myresource.yaml and apply it:
kubectl apply -f example-myresource.yaml
Operators are a method of packaging, deploying, and managing a Kubernetes application. They use CRDs to manage the lifecycle of complex applications by extending Kubernetes' capabilities. An Operator watches the state of your custom resource and makes or requests a changes to the desired state.
Operators are typically built using the Operator SDK. Here’s a simple example of how to create an Operator using the SDK:
Install the Operator SDK:
bash
brew install operator-sdk
Create a new Operator:
bash
operator-sdk init --domain=mycompany.com --repo=github.com/mycompany/my-operator
Create an API:
bash
operator-sdk create api --group=mycompany --version=v1 --kind=MyResource --resource --controller
Build and run the Operator:
bash
make install
make run
Best Practice: Always version your CRDs and manage changes carefully to avoid breaking changes for users.
Common Mistake: Forgetting to update the CRD when the spec of the custom resource changes can lead to unexpected behavior.
By mastering CRDs and Operators, you can significantly enhance the capabilities of your Kubernetes environment and tailor it to your application needs.
Task with fields name (string) and completed (boolean).Task.Task resources.completed field to true after a certain condition is met.priority (integer) to your existing Task CRD.Task instances to include this new field.