Let’s develop Kubernetes Operator in C#
Disclaimer: This article is based on my current knowledge and understanding. If you have any query or see any improvement, please mention in the comment section
Problem statement:
We can develop Kubernetes operator to do N tasks but in this blogpost, I am taking a simple example. In our example, we will create custom resource definition(CRD) which will ask user for username. Once user creates manifest using our CRD and takes apply action(kubectl apply -f manifest.yaml) on the manifest then our operator should create deployment in provided namespace. This deployment creates pod of a docker image of a sample app and adds provided username as pod labels. This is simple example but one can make CRD to take user app’s docker image in manifest and use that for deployment via operator. Similarly, if our user takes delete action(kubectl delele apply -f manifest.yaml), operator app should delete the deployment.
Implementation:
For introduction to Kubernetes Operator, please follow this link.
For understanding Kubernetes architecture, please follow this link.
Based on my experience of building operator in C#, I think developer has to focus heavily on two files(controller, entity(CRD)).
Controller is brain of the operator. It exposes two methods as shown in below image. ReconcileAsync method is called when apply action is taken on manifest. In this method, one can write his/her operator specific logic . In our example, we wrote logic to create and update deployment. DeleteAsync method deletes deployment in our example when user takes delete action on manifest.
Entity class/CRD is the class where you define properties for your CRD
Sample manifest example using above CRD
For step by step guide, please follow links from reference section.
Demo Video
- In demo video, first we saw Custom Resource Definition(CRD) manifest file.
- In second step, we applied manifest file.
- In third step, our operator app was able to recognize new manifest file and it deploys that manifest file in Kubernetes which results into creation of deployment, pod and container.
- Deployment is successful and we can see accurate logs. There is a special message for all Coldplay fans in the logs. (My friends, My wife and I tried our best to get Coldplay concert tickets but unfortunately we were not able to hence that special message).
- In consecutive step, we applied delete action on the manifest file and our operator app was able to delete it which is desired outcome.
~ Happy Coding
References: