Welcome to the Controller Pattern. In this scenario, we will learn how we can write a simple Controller just with a plain shell script.
This controller monitors all ConfigMaps which carry an annotation
k8spatterns.io/podDeleteSelector. If such a ConfigMap is modified, then all Pods which match the label-selector taken from the annotation's value will be deleted.
That way, you can support hot-pickup of your ConfigMap changes for an application that doesn't support hot reload of configuration or use the ConfigMap's values as environment variables.
Here you will learn:
- how to write a simple shell-based Controller which triggers on annotations
- how to easily talk to the Kubernetes API server from within a container with the help of a Sidecar
In this scenario, we introduced Controllers and how they can add functionality by sitting in the background and checking your resources.
We have learned ...
- ... that you can write controllers in shell script (and hence in every "real" programming language :). Please be aware though that this is just a demo project and, e.g. will fail as soon as your initial watch curl request breaks. Use a real language with some library support like from the operator-sdk for creating production-grade controllers
- ... how to access the Kubernetes API server from within a Pod, including the security setup
- ... how to run an HTTP server with
More background information about the Controller pattern can be found in our Kubernetes Patterns book. Also, don't forget to check out the examples at the books' example GitHub repository and also the Dockerfiles for the base images as they might be useful on their own.
Setup controller permissions
Before we start we need to set up permissions so that our Controller can connect to the API server and is allowed to read ConfigMap relevant events and to kill Pods
For the sake of simplicity, we are re-using the standard
edit role. For more realistic setups you should restrict the permissions for your controller to only those permissions which are required to act.
After the Kubernetes cluster is initialized, let's check the service account
config-watch-controller and the role we are using:
Let's apply them to the cluster now so that we can use it later for our Controller deployment:
kubectl apply -f rbac.yml
Now it's time to dive into the logic of our simple Controller in the next step.