Skip to main content

Tips and Tricks

Kubernetes Context & Namespace Picker with FZF​

A fast and interactive way to switch Kubernetes contexts and namespaces directly from your terminal, with Starship prompt support.

Prerequisites​

Function to Switch Contexts​

Add this to your ~/.bashrc or ~/.zshrc:

Function details
kc() {
local ctx
if [ "$#" -eq 0 ]; then
ctx=$(kubectl config get-contexts -o=name | fzf)
else
ctx=$(kubectl config get-contexts -o=name | fzf -e -1 -q "$1")
fi

if [ -n "$ctx" ]; then
kubectl config use-context "$ctx"
fi
}

Usage:

kc          # interactive selection
kc prod # pre-filled filter "prod"

Function to Switch Namespaces​

Add this to your ~/.bashrc or ~/.zshrc:

Function details
kn() {
local ns
if [ "$#" -eq 0 ]; then
ns=$(kubectl get ns -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n' | fzf)
else
ns=$(kubectl get ns -o jsonpath='{.items[*].metadata.name}' | tr ' ' '\n' | fzf -q "$1" -e -1)
fi

if [ -n "$ns" ]; then
kubectl config set-context --current --namespace="$ns"
fi
}

Usage:

kn              # interactive namespace selection
kn monitoring # switch to "monitoring" namespace

Starship Prompt Configuration​

Add to ~/.config/starship.toml:

[kubernetes]
format = '[$symbol$context(::$namespace)]($style) '
symbol = "☸ "
disabled = false

Result in the prompt:

☸ k3s-rpi::monitoring
  • Namespace is only shown if it is not default
  • You can customize symbol and format as desired