Skip to content

How it works

kswitch consists of two components:

  • kubectl-switch — the Go binary that handles context selection and kubeconfig manipulation
  • kswitch — a shell function (generated by kubectl-switch init) that wraps the binary

The shell function is the required entry point. Invoking kubectl-switch directly will print an error explaining how to set up the shell function, because the binary cannot export environment variables into the calling shell — only the shell function can do that.

For a proper installation:

  • make kubectl-switch available in your $PATH
  • source the shell function: source <(kubectl-switch init bash|zsh) (or fish/powershell equivalent)

Flow

  1. User runs kswitch (the shell function sourced from kubectl-switch init)
  2. The shell function calls the kubectl-switch binary with KSWITCH_SHELL_WRAPPER=1
  3. The binary searches for kubeconfigs in the kubeconfig stores from the SwitchConfig configuration file
  4. The binary displays a fuzzy search over kubeconfig context names
  5. The user selects a context
  6. The binary creates a temporary copy of the selected kubeconfig, sets current-context, and writes it to ~/.kube/.switch_tmp/
  7. The binary prints the kubeconfig filepath to stdout prefixed with __
  8. The shell function captures that filepath and runs export KUBECONFIG=<path>

Each terminal window operates on its own copy of the kubeconfig file (terminal isolation).

When kswitch -w (or writeToKubeconfig: true in switch-config.yaml) is used, step 6 changes: instead of writing to ~/.kube/.switch_tmp/, the selected context is merged into the real kubeconfig and current-context is set there. The shell function then exports $KUBECONFIG pointing to that real file instead of a temp file.

See Writing context to KUBECONFIG for full details.