Kubernetes: Working with multiple contexts

A context in kubernetes defines the current scope under which all the kubectl commands will run. In simple words, it defines the cluster against which all the kubectl commands will execute.

The contexts are easy to work with as long as you have a fixed number of contexts and context files. However as the number of contexts keep on growing it becomes rather difficult to manage them. In this post I will try to demystify the way of working and managing multiple contexts.

A list of all available contexts can be fetched via:

kubectl config get-contexts

Also the current context in use can be checked via:

kubectl config current-context

Similarly the current context can be switched to another one via:

kubectl config use-context <context-name>

All the above mentioned commands work well as long as all the contexts are present in the same configuration file, which is usually located at $HOME/.kube/config. This holds true depending upon the way the context was downloaded to your console. Sometimes the contexts are downloaded to different locations and in order to use those contexts, the following ways are preferred:

  • Temporary Context Switching

    You can temporary switch your context to the preferred one by setting KUBECONFIG value to the desired kube configuration location. However this will be a temporary switch and will be lost once you close your terminal/console.

    export KUBECONFIG = $HOME/.newkube/config
    kubectl config view
  • Merging Context Configuration Files

    Merging context configuration files is preferred if you would like to use the same configuration file for all your contexts. The only downside with this approach is that the configuration file might get very long as the number of contexts increase. The context configuration is usually automatically merged into the current context while downloading contexts from clusters in GKE AKS and EKS using the available CLIs.

    However to manually merge the context files, please use the following commands:

    # Backup the current kube configuration
    cp $HOME/.kube/config $HOME/.kube/config.backup.$(date +%Y-%m-%d.%H:%M:%S)
    # Include all the configuration files to merge in KUBECONFIG
    export KUBECONFIG=$HOME/.kube/config:File1:File2
    # Merge the configurations and move it to the default configuration location
    kubectl config view --merge --flatten > ~/.kube/merged_kubeconfig && mv ~/.kube/merged_kubeconfig ~/.kube/config
    # View all available contexts
    kubectl config get-contexts