two fzf-helpers for kubernetes
in howto
What it is
FZF to create zsh functions to interactively select kubernetes pods for further usage.
FZF is a nice tool for all kinds of fuzzy finding on your computer. It really shines when combined with other tools to make them interactive.
What it does for you
The two functions we create here can do the following for us:
- show all pods of a kubernetes cluster (optionally only those of a namespace)
- optinally takes an fzf query string to prepopulate fzf
- allow for fuzzy-finding the one we want with fzf interactively
- select one and then either start a bash shell in the container or show the logs for the container
The Code
function klogs() { #--argument-names pod_name namespace
local OPTIND flag
while getopts 'p:n:' flag; do
case $flag in
p) local pod_name="$OPTARG";;
n) local namespace="$OPTARG";;
esac
done
shift $(( OPTIND - 1 ))
local remaining_args="$@"
if [ -z "$namespace" ]; then
local namespace_pod=$(kubectl get pods -A | fzf --header-lines=1 -q "$pod_name"| awk '{print $1" "$2}')
local namespace=${namespace_pod%% *}
local pod=${namespace_pod##* }
else
local pod=$(kubectl get pods -n $namespace | fzf --header-lines=1 -q "$pod_name"| awk '{print $1}')
fi
if [ -z "$pod" ]; then
return
fi
echo Retrieving logs from $pod
kubectl logs -n $namespace $remaining_args $pod
}
function kbash() { #--argument-names pod_name namespace
while getopts ':p:n:' arg; do
case $arg in
p) local pod_name="$OPTARG";;
n) local namespace="$OPTARG";;
esac
done
shift $(($OPTIND - 1))
local remaining_args="$@"
if [ -z "$namespace" ]; then
local namespace_pod=$(kubectl get pods -A | fzf --header-lines=1 -q "$pod_name"| awk '{print $1" "$2}')
local namespace=${namespace_pod%% *}
local pod=${namespace_pod##* }
else
local pod=$(kubectl get pods -n $namespace | fzf --header-lines=1 -q "$pod_name"| awk '{print $1}')
fi
if [ -z "$pod" ]; then
return
fi
echo Executing bash on $pod
kubectl exec -n $namespace -it $pod -- bash
}
How to use it
Put the code into a file, e.g. fzf_k8s.zsh and source it. If you like it, add the command to source it to one of your shell initialization scripts.
Then run
kbash [-n <namespace] [-p <pod querystring>]
# or
klogs [-n <namespace] [-p <pod querystring>] [-- <other kubectl logs options>]
to find the to find the pod you wish to interact with, type some more search characters - it can be a fuzzy-find - and/or use the arrow keys to select a pod.
Then press <Enter> either start a bash shell or show the logs. Use <ESC> to exit without doing anything.
Enjoy!