While working with Kubernetes, probably the best way to access the Kubernetes cluster is by the using kubeconfig file provided by the cloud provider.
The kubeconfig file is a declarative YAML file which stores the configuration of a Kubernetes cluster. Basically, When you set up a Kubernetes cluster on a cloud, the cloud provider will provide you a kubeconfig file which helps you to get access to the cluster.
The kubeconfig files should be stored as KUBECONFIG in your bash_profile or else it needs to be under ~./kube/config folder if you are using Linux. This way, when you run kubectl get nodes or any other command then you will get output straight from the configured Kubernetes cluster to your terminal.
Another approach is to provide a kubeconfig path in every kubectl script you run. For example:
kubectl get nodes --kubeconfig={kubeconfig_path}
However when you have multiple Kubernetes cluster running on the cloud, then it can be a bit difficult to manage those kubeconfig files, since providing a kubecofig flag to every kubectl script you run can be clumsy, confusing, and difficult to maintain.
Hence, to solve this issue, we can use the Kubernetes context.
Suppose if you have multiple Kubernetes clusters running on the cloud and have different kubeconfig files then you can export all those kubeconfig files to the same KUBECONFIG variable, like below:
export KUBECONFIG=/home/aabishkar/Documents/kubernetes/kubeconfig/civo-google-microservice-kubeconfig:/home/aabishkar/Documents/kubernetes/kubeconfig/civo-kubernetes-practise-kubeconfig
Here, I have exported the kubeconfig file of two cluster name google-microservice and kubernetes-practice to the same KUBECONFIG variable.
Now, when I run the following command:
kubectl config get-contexts
This will give me contexts of both dev and prod environments.
Now to switch between different Kubernetes cluster, I just have to use a single command. For example to switch to a dev cluster:
kubectl config use-context google-microservice
This command will switch my cluster and I can now access the google-microservice cluster without providing the kubeconfig option to every kubectl script.
I hope this helps somebody.
Thank you for reading.
Top comments (1)
Awesome! I never thought to use multiple kubeconfigs and modify the kubectl context. Thanks for sharing Aabishkar! I will try it out this week.
Cheers!