Write Your Own Kubernetes Sub-Command [Part 9]by@jameshunt
170 reads

Write Your Own Kubernetes Sub-Command [Part 9]

by James HuntJanuary 30th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

You write a great script for interacting with Kubernetes. It would be great if you could pretend that your script was officially part of the kubectl repertoire.

Company Mentioned

Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Write Your Own Kubernetes Sub-Command [Part 9]
James Hunt HackerNoon profile picture

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 


You can!

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

$ kubectl fu
Error: unknown command "fu" for "kubectl"

Did you mean this?

Run 'kubectl --help' for usage.

Before it spits out the usage screen, however, 

 does a bit of spelunking through each component directory in your 
, looking for an executable file named 
. 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 

, 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 }}' "$@"
$ chmod 0755 ~/bin/kubectl-decode

$ kubectl decode creds
it's a secret to everybody.

Also seen here.