How to write a kubectl plugin

kubernetes plugins krew unused-volumes

2 min read | by Jordi Prats

Sometimes we all end up writing small one-liners to perform some daily tasks with kubectl, it can come handy to create kubectl plugin to be able to add a command that does precisely that for us. Let's see how to add a custom command to kubectl:

Let's assume you usually end up triggering a rollout restart for some deploys like this:

for i in $(kubectl get deploy --no-headers | awk '{ print $1 }' | grep pet2cattle); do kubectl rollout restart deploy $i; done

Or just all of the deploys on the namespace

for i in $(kubectl get deploy --no-headers | awk '{ print $1 }'); do kubectl rollout restart deploy $i; done

We can write a simple bash script to do so:

#!/bin/bash

restart_deploy()
{
  DEPLOY_LIST=$(kubectl get deploy --no-headers | awk '{ print $1 }' | grep "$1")

  for i in $DEPLOY_LIST;
  do
    kubectl rollout restart deploy $i;
  done
}

if [ $# -gt 0 ];
then

  if [ "$1" == "--help" ];
  then
    echo "Usage: kubectl deployrestart <namefilter>"
    exit 0
  fi

  for each in "$@";
  do
    restart_deploy $each
  done
else
  restart_deploy
fi

When kubectl doesn't have builtin the command we are requesting, it looks for executable files on the PATH named as follows:



kubectl-commandname



Hence to transform it into a kubectl plugin we just need to put this file anywhere on the PATH (for example ~/.local/bin) so that kubectl can find it. If we name it kubectl-deployrestart we will be able to use it as kubectl deployrestart:

$ kubectl deployrestart --help
Usage: kubectl deployrestart <namefilter>

Posted on 10/06/2022