Triggering shell commands or scripts on kubernetes events

How do you trigger a shell script or an ansible command when a critical pod is deleted from your kubernetes cluster?

When I was researching on how I can do something like this, I started searching for “best kubernetes event handlers”. If you do a google search for this, probably the top hits you get will be the Container Lifecycle Events and Hooks.

But my requirement was not that complex, definitely someone else must have already figured this out by now.

This led me to https://github.com/flant/shell-operator. This operator framework is quite simple, to the point and their documentation is spot on. You can easily identify what you need and whether this suits your requirements and is recognized by kubernetes.io for extending the Kubernetes functionality. You can read more about it at https://kubernetes.io/docs/concepts/extend-kubernetes/operator/

But this post is just a simple post(to be honest, my first technical post) to give you an example on how to leverage this operator pattern to make your life easier.

First lets define the problem statement — “I want to run the ansible — version command when a Deployment with the name varghese in the ns-shell-operator namespace is deleted”

deployments-hook.sh

What does this script do?

When a Deployment of name varghese is Deleted from the ns-shell-operator of your kubernetes cluster, echo “Deployment varghese is deleted” and print the ansible version.

Remember to set the hook with executable permissions

Now let’s build the docker image with this hook that we created. For this you can either use a prebuilt image flant/shell-operator:latest or build a new image with a customized version of the Dockerfile used for this image — https://hub.docker.com/r/flant/shell-operator/dockerfile

In this particular case, we will be using their prebuilt image and adding the deployments-hook.sh file and installing ansible as well. And push this docker image to a repository of your choice.

Now lets create the necessary resources in our kubernetes cluster

This includes a Deployment which runs the image that we created from the Dockerfile above.

Now lets test all this by deploying a Deployment named varghese and deleting it.

Let’s delete the deployment varghese and check the logs of the shell-operator pod in the ns-shell-operator namespace. You should see the output of the commands in the logs.