One kubectl context per shell session

Context switching is no fun. Be it the kernel/user mode switching, multiple tasking at work or changing between kubectl contexts. It’s an overhead that should be eliminated or at least reduced.

I deal with multiple Kubernetes clusters on a daily basis. Without some nice tools/tricks, switching between these clusters is tedious and dangerous. If not careful, a deadly command could be carried out on a totally unexpected cluster.

What I have today, in terms of tools, are kube-ps1, kubectx and kubens. In zsh, it looks like:

These are all good. No kidding, these goodies have been making my life so much easier. It’s very easy to switch between contexts and it always shows in the prompt. But, there is one problem it doesn’t solve. It’s the constant context switching. Even it’s little effort to switch, it adds up when you have to do it hundreds of times.

Every kubectl context switch is global. It is an actual change of the kubeconfig file after all. It would be really nice if we can stick to one context in a shell session and a different contex in another session. Recently, I have discovered a technique that achieves this. Simply adding this snippet to the .zshrc file:

# kubeconfig per session
file="$(mktemp -t "kubectx.XXXXXX")"
export KUBECONFIG="${file}:${KUBECONFIG}"
cat <<EOF >"${file}"
apiVersion: v1
kind: Config
current-context: ""
EOF

It’ll create a temporary kubeconfig file for each zsh session and contains the context information without impacting any other sessions.

A game changer.

One kubectl context per shell session

One thought on “One kubectl context per shell session

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s