Using one kubeconfig per context with kubectl
Managing the configuration files for many k8s contexts can become a bit cumbersome. And while there are plugins and tools that can manage them for you there is actually already a feature built into kubectl that allow us to split up our kubeconfig files into as many files as we want.
From the kubectl-config man pages: If $KUBECONFIG environment variable is set, then it is used a list of paths (normal path delimitting rules for your system).
That means that as long as we automate populating $KUBECONFIG with a semicolon delimited list (works for Linux and Windows), we can have how many kubeconfig files as we want.
That can easily be done for both Linux and Windows by putting a snippet at the bottom of ~/.bashrc for bash or in your $PROFILE file for powershell.
~/.bashrc
# Load in all kubeconfig files in $HOME/.kube
export KUBECONFIG=""; for entry in $(ls --hide="cache" $HOME/.kube); do export KUBECONFIG="$HOME/.kube/$entry:$KUBECONFIG"; done;
Powershell $PROFILE
# Load in all kubeconfig files in $HOME\.kube
$env:KUBECONFIG = (Get-ChildItem "$HOME\.kube" -File | ForEach-Object { $_.FullName }) -join ";"
After re-sourcing my profile, or simply restarting my terminal emulator i can now have a ~/.kube directory that looks like this:
bash output
❯ ls -al
total 40
drwxr-xr-x 3 zacke zacke 4096 Oct 23 10:38 .
drwxr-x--- 24 zacke zacke 4096 Oct 22 12:50 ..
drwxr-x--- 5 zacke zacke 4096 May 5 14:32 cache
-rw-r--r-- 1 zacke zacke 60 Oct 5 09:11 config
-rw-r--r-- 1 zacke zacke 1416 Oct 23 10:09 cluster01-oidc.kubeconfig.yaml
-rw-r--r-- 1 zacke zacke 1446 Oct 23 10:11 cluster02-oidc.kubeconfig.yaml
-rw-r--r-- 1 zacke zacke 2454 Oct 23 10:38 cluster03-oidc.kubeconfig.yaml
-rw-r--r-- 1 zacke zacke 2455 Oct 23 10:15 cluster04-oidc.kubeconfig.yaml
-rw-r--r-- 1 zacke zacke 791 Oct 5 09:11 minikube.kubeconfig.yaml
Where ~/.kube/config simply keeps track of the currenct context, while the others contain my actual connection info:
~/.kube/config
apiVersion: v1
kind: Config
current-context: cluster01
On top of being very simple it's also easy to carry around the configuration reading setup by including it with my dotfiles. Then all I have to do on a new machine is to download the kubeconfig from my password manager and put it in the right directory.