Trick #9 – Write Your Own Sub-Command

Ahoy, There!

This is just one blog post in an ongoing series about fun things you can do with the Kubernetes CLI, kubectl. We have a whole bunch of these over on our Silly Kubectl Tricks page. Also don’t forget to checkout out the video series on YouTube!

Eventually, you’ll write a super handy script for interacting with Kubernetes – I have no doubt. Wouldn’t it be stellar if you could pretend that your script was officially part of the kubectl repertoire?

You can!

kubectl is a multi-call binary, in the same fashion as git. When you call it with a sub-command it doesn’t intrinsically recognize, it tells you:

$ kubectl fuError: unknown command "fu" for "kubectl"
Did you mean this?
Run 'kubectl --help' for usage.

Before it spits out the usage screen, however, kubectl does a bit of spelunking through each component directory in your $PATH, looking for an executable file named kubectl-$COMMAND. We can use this to our advantage:

$ echo $PATH
$ cat ~/bin/kubectl-fu
echo "the kubernetes is strong with this one..."
$ kubectl fu
the kubernetes is strong with this one...

It doesn’t matter what you write your program in; hack up some Bash, compile some Go or Rust, even write it in Perl or Python! As long as it is in $PATH, and has the executable bit set, you can pretend to be a core CLI author!

Here’s a more potent and useful example, which uses a bit of Go magic to handle the base64 encoding that Kubernetes puts on all of its Secrets.

If you store secrets in Kubernetes, they get encrypted at rest, and are returned by the API encoded using the Base 64 scheme. While the particulars of the algorithm are interesting, using the encoded data is a bit of a pain.

$ kubectl get secret creds -o jsonpath='{.data.password}'

Luckily, we can use Go templates to format data we get from the API. What’s more, the template language has the ability to decode base64-encoded data, natively! Here’s a first attempt at extracting the data:

$ kubectl get secret creds -o template='{{.data.password | base64decode }}'
it's a secret to everybody.

That’s mighty useful. If we package it up as the new kubectl decode sub-command, it gets 10x more useful!

$ cat ~/bin/kubectl-decode
exec kubectl get secret -o template='{{.data.password | base64decode }}' "[email protected]"
$ chmod 0755 ~/bin/kubectl-decode
$ kubectl decode creds
it's a secret to everybody.

Spread the word

twitter icon facebook icon linkedin icon