Most people using Kubernetes extensive have already defined alias k=kubectl
and are using tools like kubectx
.
As someone really lazy though, I have found/developed a few less common tools to help work with Kubernetes efficiently.
kubectl apply
from clipboard
This relies on zsh
, and uses the zle
to define a custom command.
function zle_apply {
LBUFFER=" cat <<EOF | kubectl apply -f -
$(xclip -se c -o)
EOF"
CURSOR=31
}
zle -N zle_apply; bindkey "^k" zle_apply
This defines a function and binds it to Ctrl+k
.
This will get us one "enter" away from applying whatever we have in our clipboard. We could just apply it in a single hotkey, but that seems a bit reckless.
The cursor is also conveniently moved to just after the -f -
in case we want to set any other flags.
Picking pod names with fzf
fzf
is a "command line fuzzy finder", useful for... finding things.
Here, we can use it to find a Pod name, and insert it into our current command line:
# First, define a function that sends all pods to `fzf`.
# Once it picks a row, extract the 1st column (the pod name).
function fkp () {
pods=$(set -o pipefail; kubectl get pods --no-headers ${@}) || return 1
fzf --nth 1,2 <<< $pods | awk '{print $1}'
}
# Now define a ZLE function that just calls this and inserts the result into our buffer
function zle_fkp {
res=$(fkp) || return 1
LBUFFER="${LBUFFER}${res} "
zle reset-prompt
}
# Finally, bind it to Alt+k
zle -N zle_fkp; bindkey "^[k" zle_fkp
Its easier show this:
This avoids typing part of a command, realizing we need a pod name, running another command, selecting the name, and copying it over. This could be generalized to other resources as well, but I operate with pods a lot.
Grepping YAMLs
kubectl grep
is a handy tool for grepping through Kubernetes YAMLs, and has grown beyond YAML.
For example, summarizing all resources:
$ helm template istio/istiod | k grep -s
PodDisruptionBudget/istiod.default
ServiceAccount/istiod.istio-system
ConfigMap/istio.default
ConfigMap/istio-sidecar-injector.default
Searching for a literal within objects, and stripping fields that are not commonly needed (managedFields
, last-applied-configuration
, etc):
$ kubectl get pods -A -oyaml | k grep -r runAsNonRoot -N
apiVersion: v1
kind: Pod
metadata:
annotations:
...
Log Helpers
log-helper
is like grep, but instead of filtering matches, it highlights them.
Another nice feature is the -k
flag - replacing all IP addresses with the name of the Kubernetes resource it refers to - highlighting it in the process, of course.
So something like remoteAddr=10.36.2.4
becomes remoteAddr=shell-dc477d7c-k88dm
. Much better.
Finalizers
finalizers
is a two-for-one - a nice tool to find "stuck" resources, and a fitting description for how I feel about finalizers
.