Adding a function to your .bashrc for resource switching

Shout out to my friend Drew for this one – I had something similar (but nowhere near as cool) previously!

In my work environment, we have several different kubernetes clusters that my team manages. It’s relatively common to have to switch between them several times a day because of various work items that need completed. Aside from that, there are different namespaces within each environment as well, also which need to be specified. This usually comes in the form of one or two commands:

kubectl config use-context dev-env
kubectl config set-context --current --namespace mynamespace

(You can condense these down into one command, but I’m leaving it as two for simplicity.)

In any event, these commands need to be executed every time you switch from test to dev, from dev to prod, or whatever your environments are, along with the namespaces as well. Each cluster requires a yaml file downloaded from the cluster that contains all of the information kubectl needs to know what cluster to connect to, along with your credentials. This .bashrc function is a very elegant and simple way to be able to switch environments and/or namespaces with a single command:

clus() {
    if [ $# != 2 ]; then
    echo "usage: clus <environment> <namespace>" 1>&2
    return 1
fi
environment=$1
namespace=$2
if ! [[ "${environment}" =~ ^(dev(1|2)|test(1|2)|prod(1|2))$ ]]; then
    echo "error: invalid environment \"${environment}\"" 1>&2
    return 1
fi
if ! [[ "${namespace}" =~ ^(name1|name2|name3) ]]; then  
    echo "error: invalid namespace \"${namespace}\"" 1>&2
    return 1
fi
export KUBECONFIG=${HOME}/workspace/kubeconfigs/${environment}.yaml
kubectl config use-context "${environment}"-fqdn
kubectl config set-context --current --namespace "${namespace}"
}
export -f clus

So needless to say, I’ve obscured some of the company-specific details about our namespace and cluster names, but you get the idea. So now any time I’ve got an active terminal, all I have to do is type:

clus dev2 name3

And I’m configured for the dev2 environment and the name3 namespace. Messages are displayed on the screen to indicate success.

Just remember! You need to have downloaded your cluster yaml files into a directory (here mine is /home/username/workspace/kubeconfigs) for this to work!

Leave a Reply

Your email address will not be published. Required fields are marked *