Lab: Create and Use a Custom Resource Definition (CRD)
Goal
Create a Fruit
CRD that allows you to define fruits like apple
, banana
, etc., and deploy a controller that prints them.
Prerequisites
- Kubernetes cluster (e.g. Minikube)
kubectl
installed- Optional:
kustomize
andcontroller-gen
if building a full controller
Lab Structure
crd-lab/
โโโ crds/
โ โโโ fruit-crd.yaml
โโโ examples/
โ โโโ apple.yaml
โโโ controller/
โโโ fruit-controller.sh
Define the CRD
๐ crds/fruit-crd.yaml
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: fruits.example.com
spec:
group: example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
color:
type: string
taste:
type: string
subresources:
status: {}
scope: Namespaced
names:
plural: fruits
singular: fruit
kind: Fruit
shortNames:
- frt
Apply the CRD:
kubectl apply -f crds/fruit-crd.yaml
Create a Custom Resource (CR)
๐ examples/apple.yaml
apiVersion: example.com/v1
kind: Fruit
metadata:
name: apple
spec:
color: red
taste: sweet
Apply the CR:
kubectl apply -f examples/apple.yaml
Verify:
kubectl get fruits
kubectl get fruit apple -o yaml
Create a Simple Controller (optional)
This is a demo controller (bash script) that watches the fruit CRs and prints them. In real apps you'd use a proper controller with client-go
or Kubebuilder.
๐ controller/fruit-controller.sh
#!/bin/bash
echo "Watching for Fruit resources..."
kubectl get fruit --watch -o json | jq -c '.'
Run:
bash controller/fruit-controller.sh
Then try creating more fruits:
# examples/banana.yaml
apiVersion: example.com/v1
kind: Fruit
metadata:
name: banana
spec:
color: yellow
taste: sweet
kubectl apply -f examples/banana.yaml
Clean Up
kubectl delete -f examples/
kubectl delete -f crds/
Summary
Component | Description |
---|---|
Fruit CRD | Defines the structure of a fruit |
Custom Resources | Concrete fruit instances |
Controller | Watches and prints changes |