View Your Current a Kubernetes `kubectl` Cluster Context on the CLI
When I first started using git
many years ago, you would be working pretty blind on the command line (and I don't know of any GUI tools at the beginning). So, to make sure you didn't commit anything to the wrong branch, you would be constantly checking git status
to see your branch. Then people created the git_branch PS1 command and it showed as part of your prompt. I couldn't find a working one for the same thing with a kubectl context, so I created this:
#!/bin/bash
__kube_ps1()
{
# As a k8s beginner, I'm worried I'm going to be
# in the wrong context and issue some apply command
# or helm install/upgrade. Thus, I first must export
# which kubeconfig I'm using. I have one for dev, stage,
# prod and local (kind).
# See below for a context-switch helper
if [ -z "$KUBECONFIG" ]; then
echo "[k8s: kcontext ? || KUBECONFIG=~/.kube/?]"
else
CONTEXT=$(kubectl config current-context)
if [ -n "$CONTEXT" ]; then
echo "[k8s: ${CONTEXT}]"
fi
fi
}
I put it in here with sudo vi /usr/local/bin/kube-prompt.sh
Then I updated my ~/.bashrc
file as such:
source /usr/local/bin/kube-prompt.sh
export PS1='${bgSilver}${fgBlack} \w ${bgPowderBlue}${fgWhite}$(__git_ps1) ${_BOLD}${bgYellow}${fgRed} $(__kube_ps1) ${_RESET}\n\$ '
# This is to set this to a default of empty, but exported into the global
# variable scope
export KUBECONFIG=""
# This function you run like: `kcontext dev` or, to clear, `kcontext none`
kcontext() {
KUBECONFIG=~/.kube/$1config
if [[ $1 == 'none' ]]; then
KUBECONFIG=""
fi
}
See my backup of my .bashrc
file in a previous post for the color definitions, etc. Also the __git_ps1
is part of the well-worn git installation.
Now, to define your environment, you would do kcontext dev
and $KUBECONFIG
would point to ~/.kube/devconfig
and also show the context in your prompt. If you have multiple dev contexts, you can still change it with kubectl config get-contexts
to find the name of one, then kubectl config use-context <context-name>
to change. Otherwise, to change from one environmen to another, you would have a file for each cluster context (eg ~/.kube/prodconfig, ~/.kube/devconfig, etc).