0

I need to access several Kubernetes clusters. For each of them, I got a kubeconfig yaml file, e.g. kubeconfig-cluster1.yaml and kubeconfig-cluster2.yaml.

How can I easily switch between these configurations? I mean, without setting the KUBECONFIG environment variable manually to one of these files?

Pierre F
  • 1,332
  • 15
  • 33
  • General KUBECONFIG tips by the developer of the kubectx utility: https://medium.com/@ahmetb/mastering-kubeconfig-4e447aa32c75 – Pierre F Feb 12 '20 at 10:51
  • Also have a look at the direnv tool which lets you automatically set environment variables based on the directory tree you’re in: https://direnv.net – Pierre F Feb 12 '20 at 10:53

2 Answers2

1

You can declare all contexts in the KUBECONFIG environment variable:

The KUBECONFIG environment variable holds a list of kubeconfig files. For Linux and Mac, the list is colon-delimited. For Windows, the list is semicolon-delimited.

To autodetect the contexts based on the kubeconfig files, assuming they're all located in the ~/.kube folder, and assign them as a colon-separated list to the KUBECONFIG environment variable, you could add a script to your ~/.bashrc or ~/.zshrc:

# Autodetect kubeconfig files to enable switching between them with kubectx
export KUBECONFIG=`ls -1 ~/.kube/kubeconfig-* | paste -sd ":" -`

Then, to switch between these kubectl contexts (with autocomplete!), have a look at the kubectx utility. The kubectx README page contains installation instructions.

$ kubectx cluster1
Switched to context "cluster1".
$ kubectx cluster2
Switched to context "cluster2".
Pierre F
  • 1,332
  • 15
  • 33
0

I also had multiple kubernetes cluster to manage. I wrote a script to switch kubeconfig and namespace easily. Hope it can help you.

. k-use -k <kubeconfig> -n <namespace>

https://github.com/kingonion/k-use

Kingonion
  • 1
  • 1