Tired of stringing together a bunch of Kubernetes commands? Consider consolidating them into a custom kubectl plugin. In this post, I'll show you how easy this can be.
You might already be using kubectl plugins. Not sure? Type kubectl plugin list to find out. If you've got any, you'll get a list of executables, all named kubectl-<something>.
kubectl plugins are surprisingly easy to create.
To write one of your own, copy this into a new file called kubectl-greeting:
kubectl create ns "$1"
echo "Hello, $1. You have your own namespace!"
Make the file executable and move it anywhere on your $PATH. For example:
chmod +x kubectl-greeting && mv kubectl-greeting /usr/local/bin/
Then type kubectl greeting friend. Ta da! You're plugged into the kubectl CLI. Nice job!
Get fancy with subcommands, helper libraries, REST requests, and best of all: other people's plugins.
Here are three tips to help you make the most of kubectl plugins.
1. Subcommands are controlled via filenames.
echo -e '#!/bin/bash\nkubectl delete ns $1' \
chmod +x /usr/local/bin/kubectl-greeting-goodbye
Then type kubectl greeting goodbye friend. Easy, huh?
For those of you on your mobile phones, here's what you would see so far if you were trying this at your computer:
~$ kubectl greeting friend
Hello, friend. You have your own namespace!
~$ kubectl greeting goodbye friend
namespace "friend" deleted
2. Nothing beats a good example.
Check out the repo github.com/kubernetes/sample-cli-plugin for an example of how to use "cli-runtime" helper libraries, make REST calls to the Kubernetes API server, and follow good kubectl patterns.
3. Community Index. A plethora of good examples!
You don't really have to write your own. You can just use one of of the many plugins provided be the ever-generous open source community. There's a package manager called krew (memory hint: sounds like brew) to help you search, install, and upgrade open source plugins. You can also peruse the list here: krew.sigs.k8s.io/plugins. (Proceed with a bit of caution as there's no security auditor checking these little puppies out.)
Some of my favorites include tree (shows hierarchy of resources spawned), lineage (same plus event info), view-secret (decodes secrets so you don't need to bother with base64 decoding), assert (handy for verifying things are as you expect), and rbac-lookup (figure out which roles apply to a given service account).
Hopefully you'll find plugins that make your workflows more productive, and now you know how easy it can be to create them as well. Whether you're writing your own or checking out the community index, I'd love to hear what your favorite plugins are!