/ kubernetes

How to write custom controller for kubernetes

Kubernetes Custom Controller runs inside the Controller Manager on the master node. This controller listens for configuration requests for the custom resource.One of the ways in which you can extend Kubernetes is by writing your own custom controllers. You can write custom controllers that handle in-built Kubernetes objects, such as Deployment, Service, in new ways, or you can add new custom resources within Kubernetes and write a custom controller to handle these new resources.

It is responsible for deploying and maintaining pods that belong to custom resource.
Work flow of custom controller:

  1. Construct informer and shared informer objects
  2. Controller monitor for events on crd
  3. Modify the resource to expected state and perform actions.

Pictorial representation of componentes involvedkubernetes

Construct informer and shared informer objects::

*queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())

informer := cache.NewSharedIndexInformer(
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return client.CoreV1().Pods(metav1.NamespaceAll).List(options)
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return client.CoreV1().Pods(metav1.NamespaceAll).Watch(options)
0, //Skip resync

Monitor for Events on resources::

AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
DeleteFunc: func(obj interface{}) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {

Here resource controller push the object keys to worker queue for processing. Controller which is running will pick the object keys from queue and process items as per the business logic.