Kube context for everyone!

October 27, 2021

Why isolated context?

Typically when you switch context in kubectl (with ex. kubectx), the change happens on all terminal instances. That is because the change is saved in your $HOME/.kube/config file and is read on every interaction with kubectl.

This will lead to the inevitable scenario of working on a local cluster, and needing to do something quickly in production. You open another terminal, switch context, do your work and then go right back to your old terminal. The issue is that the prompt has not visually refreshed to the actual context. Often the following command you type will not be dangerous, and you will notice that you did it in production, but sometimes the damage is severe💥.

Using this imperfect script, we will use environment variables to decide what context we should use instead of the config file mentioned above. Each context will need its config file, just a copy of the original appended with the context name ex. config-dev, config-prod.

#!/bin/bash

switch_context () {
  # This will discard the output from our background calls to kubectx 
  stty flusho; command ;stty -flusho
  
  # Get current context
  oldCTX=$(kubectx -c) 

  # Ask for the new context
  kubectx 

  # Save the new context
  CTX=$(kubectx -c)

  # Reset the state since we don't want to change the original config file 
  kubectx $oldCTX >/dev/null

  # Check what config we want to use
  # TODO: Should be done dynamically instead of a if/else statement
  if [[ $CTX == *"dev"* ]]; then
    export KUBECONFIG=$HOME/.kube/config-dev
  elif [[ $CTX == *"prod"* ]] then
    export KUBECONFIG=$HOME/.kube/config-prod
  elif [[ $CTX == *"delivery"* ]] then
    export KUBECONFIG=$HOME/.kube/config-delivery
  else
    export KUBECONFIG=$HOME/.kube/config
  fi

  kubectx $CTX >/dev/null;
}

And in your .zshrc, .bashrc file:

alias Switch="switch_context"

source ~/switch_context.zsh

Results:

Kubectl_Context

Improvements:

  • âž• With a little more effort, we could remove the kubectx dependency.
  • âž• Context should be dynamically set up i.e., read config file to figure out the context used and create the files needed.

Drawbacks

  • âž– We are using kubectx call three times to do the result of one call essentially.