Posted on :: Updated on :: 383 Words :: Tags: , , , ,

If you work with multiple Kubernetes clusters, you probably have several kubeconfig files. Switching between them can be a pain. This post shows you a simple script that uses fzf (a command-line fuzzy finder) to make switching between your kubeconfig files fast and easy.

What You Need

Make sure you have these two tools installed:

  • kubectl: The command-line tool for Kubernetes.
  • fzf: A tool for quickly searching for things on the command line.

The Script

Save the following script in a file. A good name for it is kswitch in your home directory (~/kswitch).

#!/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"

How to Set It Up

To make the script work, you need to create an alias. An alias is a shortcut for a longer command.

Add this line to your shell startup file (either ~/.bashrc or ~/.zshrc):

alias kswitch='source ~/kswitch'

Why source? The source command runs the script in your current terminal session. This is important because it allows the script to set the KUBECONFIG environment variable for you.

After adding the alias, reload your shell by closing and reopening your terminal or by running source ~/.bashrc (or source ~/.zshrc).

How to Use It

  • Run kswitch in your terminal. A menu will appear, letting you choose a kubeconfig file and then a context.
  • You can also run kswitch /path/to/your/kubeconfig to select a specific file directly.