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 fu
Error: unknown command "fu" for "kubectl"
Did you mean this?
run
cp
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
/Users/jhunt/bin:/usr/bin:/bin:/usr/sbin:/sbin
$ cat ~/bin/kubectl-fu
#!/bin/sh
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}'
aXQncyBhIHNlY3JldCB0byBldmVyeWJvZHku
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
#!/bin/sh
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.