Skip to content

Instantly share code, notes, and snippets.

@pvdb
Last active May 8, 2025 07:49
Show Gist options
  • Save pvdb/813b5ba5bb1383c526d9dbcde64c9878 to your computer and use it in GitHub Desktop.
Save pvdb/813b5ba5bb1383c526d9dbcde64c9878 to your computer and use it in GitHub Desktop.
kubectl wrapper
#!/usr/bin/env zsh
#
# INSTALLATION
#
# ln -s ${PWD}/kubektl $(brew --prefix)/bin/
# sudo ln -s ${PWD}/kubektl /usr/local/bin/
#
# set -euxo pipefail ;
current_context=$(command kubectl config current-context) ;
> /dev/tty printf "Current context: \"%s\".\n" "${current_context}" ;
kube_context() {
label=$(echo "Select a kube context ..."|lolcat -f) ;
command kubectl config view | yq '.contexts[].name' | \
fzf --bind backward-eof:abort --height="~100%" --border --border-label="> ${label} <" ;
}
selected_context=$(kube_context) ;
[ -z "${selected_context}" ] && selected_context="${current_context}" ;
context="--context=${selected_context}" ;
> /dev/tty printf "Selected context: \"%s\".\n" "${selected_context}" ;
kube_namespace() {
label=$(echo "Select a kube namespace ..."|lolcat -f) ;
command kubectl "${context}" --output=json get namespaces | \
jq -r '.items[].metadata.name' | \
# jq -r '.items[] | select(.status.phase=="Active") | .metadata.name'
fzf --height="~100%" --border --border-label="> ${label} <" ;
}
kube_pod() {
label=$(echo "Select a kube pod ..."|lolcat -f) ;
command kubectl "${context}" --output=json --namespace "${namespace}" get pods | \
jq -r '.items[]|.metadata.name' | \
# jq -r '.items[] | select(.status.phase=="Running") | .metadata.name'
fzf --height="~100%" --border --border-label="> ${label} <" ;
}
pod_container() {
label=$(echo "Select a pod container ..."|lolcat -f) ;
command kubectl "${context}" --output=json --namespace "${namespace}" get pods "${pod}" | \
jq -r '.spec.containers[].name' | \
fzf --height="~100%" --border --border-label="> ${label} <" ;
}
case $1 in
"exec")
namespace=$(kube_namespace) ;
pod=$(kube_pod) ;
container=$(pod_container) ;
command kubectl "${context}" exec -it --namespace "${namespace}" "${pod}" --container "${container}" -- /bin/sh ;
;;
"logs")
namespace=$(kube_namespace) ;
pod=$(kube_pod) ;
container=$(pod_container) ;
command kubectl "${context}" logs -f --namespace "${namespace}" "${pod}" --container "${container}" ;
;;
"delete")
namespace=$(kube_namespace) ;
pod=$(kube_pod) ;
command kubectl "${context}" delete pod --namespace "${namespace}" "${pod}" --now --interactive ;
;;
*)
command kubectl "${context}" "$@" ;
;;
esac
# That's all Folks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment