Kubectl config helpers

If you manage multiple k8s clusters you have no doubt tinkered with different ways to store and use the config files.

Below is my preferred method of wrangling them and how I switch between them effectively.

In my ~/.kube directory I have individual configs for each cluster and a config file with null values. This config file with null values is used as a placeholder and gets updated when thecurrent-context changes. This is preferable to having the current context updated in a seemingly random config file.

~/.kube/config

apiVersion: v1
clusters: null
contexts: null
current-context: Trowbridge-k0s
kind: Config
preferences: {}
users: null

Your individual cluster configs will reside in the ~/.kube directory as well and will have a filename prefix of config

~/.kube/config-example

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: somesupersecretstring
    server: https://example.com:16443
  name: Example
contexts:
- context:
    cluster: Example
    user: Example
  name: Example
kind: Config
preferences: {}
users:
- name: Example
  user:
    token: somesupersecretstring

Notice the example config does not have a current-context line

For this to work you will need to make a slight modification to your terminal profile. .bash_profile / .bashrc / etc.

# load all the config files in the .kube directory
export KUBECONFIG=$(find ~/.kube -name 'config*' | sort | tr '\n' ':')

This line is iterating over the ~/.kube directory and grabbing files that begin with config and sorting them so that the config proper file is loaded first.

With that, kubectl has access to all your configs and they are nicely separated and easy to work with.

Helper Script

Add the following either as a bash function in your profile or as a shell script that is linked to an alias to make context switching a breeze.

ktx.sh

#!/usr/bin/env bash

red=$(tput setaf 1)
gold=$(tput setaf 3)
blue=$(tput setaf 4)
magenta=$(tput setaf 5)
cyan=$(tput setaf 6)
default=$(tput sgr0)

# ensure kubectl is installed
if ! hash kubectl 2>/dev/null
then
  echo "${red}You need kubectl installed${default}"
  exit 0
fi

CONTEXTS=( $(kubectl config get-contexts | awk 'NR!=1''{print $2}') )

PS3="${cyan}Select a kubectl context (q to quit): $gold"
select context in "${CONTEXTS[@]}"; do
  case "$context" in
    "") break ;;  # This is a fake; any invalid entry makes $context=="", not just "q".
    *) break ;;
  esac
done


if [ ! -z "$context" ]
then
  kubectl config use-context $context > /dev/null
  echo "${blue}Kubectl Context switched to [${magenta}$context${default}]"
fi