Easily switch between kubeconfigs with kswitch.
Table of Contents
Set Up Alias
To integrate kswitch
into your shell and expose relevant environment variables, add this alias to your.bashrc
or .zshrc
:
alias -- kswitch='source kswitch'
Script functionality
The script below allows you to seamlessly select and switch between Kubernetes configuration files located in your $HOME/.kube/
directory using fzf.
#!/usr/bin/env bash
SEARCH_PATH="$HOME/.kube/"
IGNORE_LIST=()
ignore=()
for i in "${IGNORE_LIST[@]}"; do
ignore+=("!" "-path" "$i")
done
if [[ $# -eq 1 ]]; then
selected="$1"
else
files=$(find "$SEARCH_PATH" -mindepth 1 -maxdepth 1 -name '*config*' -type f "${ignore[@]}" 2>/dev/null)
selected=$(fzf-tmux -p 85% --reverse --preview 'cat {}' <<<"${files[@]}" | sort -u)
fi
if [[ -z "$selected" ]]; then
echo "No kubeconfig selected."
exit 0
fi
export KUBECONFIG="$selected"
export KUBE_CONFIG_PATH="$selected"
selected_name=$(basename "$selected" | tr . _)
echo "Selected kubeconfig: $selected_name"
contexts=$(kubectl config get-contexts --kubeconfig="$selected" -o name)
if [[ -z "$contexts" ]]; then
echo "No contexts found in $selected!"
exit 1
fi
context_count=$(echo "$contexts" | wc -l)
if [[ "$context_count" -eq 1 ]]; then
selected_context="$contexts"
echo "Automatically selecting the only available context: $selected_context"
else
selected_context=$(echo "$contexts" | fzf-tmux -p 60% --reverse)
if [[ -z "$selected_context" ]]; then
echo "No context selected."
exit 0
fi
fi
kubectl config use-context "$selected_context" --kubeconfig="$selected"
By setting up the alias and using this script, you can efficiently toggle between different Kubernetes configurations without having to manually change environment variables every time.