Build Kubernetes Controller to Provision PVC using Kubebuilder

Sonu Singh
2 min readSep 23, 2021

A controller tracks at least one Kubernetes resource type. These objects have a spec field that represents the desired state. The controller(s) for that resource is responsible for making the current state come closer to that desired state.

If you want more details about Kubernetes controller check this link:[https://kubernetes.io/docs/concepts/architecture/controller/]

Demo

In this demo, we are going to create a controller to watch Pods event and if any new pod gets created controller will check that if the Pod status is pending and Pod is requesting a PVC(Persistent Volume Claim), then the controller will provision a PVC for that pod with a predefined volume size with the name defined in Pod Spec.

Flow Digram of Controller
Flow Diagram of Controller

Prerequisites

  • Kubebuilder v3.1.0
  • kubectl v1.21.2
  • Go v1.16.7
  • A cloud node up and running

Create a Project and API

Create a directory, and then run the init command inside of it to initialize a new project.

mkdir pod-pvc
cd pod-pvc
go mod init pod-pvc
kubebuilder init --domain example.com

Run the following command to create a new API (group/version) as batch/v1 and the new Kind(CRD) PvcCon on it:

kubebuilder create api --group batch--version v1 --kind PvcCon

Implement the Controller Logic

Now to implement the controller logic go to file controllers/pvccon_controller.go and then add the controller logic in the ‘Reconcile’ function as follows:

First, get the list of all the pods:

Now get all the pods that are in the pending state:

Provisioning PVC for each pod:

The controller will be running locally.

At this stage, if you create any Pod or Deployment which requires any PVC then the controller will provision the PVC with a default size for each of the Pods.

Run It On the Cluster

To run the controller on any remote machine we need to create docker and deploy it.

make docker-build docker-push IMG=<some-registry>/<project-name>:tag
make deploy IMG=<some-registry>/<project-name>:tag

You can get the code and test files in the article on Github. [https://github.com/acumino/kubernetes-controller]

References

--

--