kubectl plugins
2020-08-11
Following the kubernetes
management theme, there's something that may be of
interest for kubectl
users.
That management tool accepts what they call plugins. Those are simply
executables that reside in $PATH
, and they follow a naming convention, that is
kubectl-name
. Where name
is a subcommand you want to create.
Sub-sub-commands can nested by creating executables with the form
kubectl-sub-sub-command
(so dash separated words for them).
They can be compiled binaries written in your language of choice, or scripts made in your preferred interpreted programming language.
I use this to simplify or wrap around existing subcommands, for tasks that I do regularly and annoy me, but can be used to develop new functionalities.
For reference, this is the official documentation I'll show a couple of examples here.
Restart a deployment
This one is as simple as it gets. Actually there's no way of restarting a deployment on kubernetes. Pods are (or should be) stateless and expendable, so you really kill them and the scheduler re-creates them when the deployment definition requirements are not met.
A simple way of "emulating" a restart, is modifying the deployment so the scheduler re-creates all the pods in it. For that, just changing the value of an environment variable in the deployment definition will suffice. For that I created this plugin:
#!/bin/sh
set -eu
usage() {
echo "kubectl restart <deployment>"
exit 1
}
deployment=${1:-x}
test $deployment != "x" || usage
kubectl set env \
"deployment/$deployment" \
LAST_MANUAL_RESTART="$(date +%Y%m%d.%H%M%S)"
Custom log output
Even with all the log aggregation and the cloudy stuff doing cloudy things, one
sometimes needs to take a peek at the logs of an specific container. That can
be done with the kubectl logs
command, which will dump all the things to your
terminal.
Some of the apps at work spit out some sort of structured JSON as logs, which is hard to read when they come in one line and without any time stamp on them. For that I created this:
#!/bin/sh
set -eu
if ! command -v jq > /dev/null; then
echo 'You need to have jq installed to run this plugin.'
exit 1
fi
usage() {
echo "kubectl pslog <pod> [container] [options]"
echo "(options can be any option passed to kubectl logs)"
exit 1
}
pod=${1:-x}
test $pod != "x" || usage
kubectl logs $* |\
grep -E '^{' |\
jq -r '"\(.timestamp.seconds | strftime("%Y-%m-%d %H:%M:%S %Z")) | \(.message)"'
kubectl pslog
uses the power of jq
to print the time stamp in a human
readable manner in front of each log entry, and then prettifies it in the
process, which is way more readable.
Not much more to say, hope this gives you some ideas to make your life easier
when using kubectl
.
Have any comments ? Send an email to the comments address.