Silly Kubectl Trick #9: Write Your Own Sub-Command
Wouldn't it be stellar if you could pretend that your script was officially part of the kubectl repertoire? You can!
Join the DZone community and get the full member experience.Join For Free
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 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:
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:
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.
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:
That's mighty useful. If we package it up as the new
kubectl decode sub-command, it gets 10x more useful!
Published at DZone with permission of . See the original article here.
Opinions expressed by DZone contributors are their own.