In the last post, I shared my context-specific direnv+asdf config for managing interpreters and tools. Since writing that, I attempted to add kubernetes contexts to the mix, and found only dubious advice from other folks advocating wrapper scripts and other oddities.
It’s poorly documented and somewhat counterintuitive, but kubectl
supports multiple configuration files in the KUBECONFIG
environment variable. Unlike most other unix-like applications however, it treats those configuration files almost exactly backwards – the first definition wins. But it’s enough to get the job done.
First, we create an overlay configuration file, with the minimum amount duplicated from ~/.kube/config
.
Here’s the contents of ~/.kube/overlay/project-cluster-namespace
. Name and path are completely arbitrary, but I do like to be organized.
contexts:
- context:
cluster: gke_cluster_name
namespace: my-application-namespace
user: gke_authentication_bits
name: my-favorite-context
current-context: my-favorite-context
From there, one need only add a KUBECONFIG
environment variable to .envrc
as follows:
export KUBECONFIG="${HOME}/.kube/overlay/project-cluster-namespace:${HOME}/.kube/config"
Entering the directory with direnv hooks active will yield the following:
direnv: loading ~/projects/my-application
direnv: export +KUBECONFIG
The result is a context-specific cluster and namespace without having to deal with clunky kubectl
wrapper scripts or extra files in the workspace, and no side effects for other sessions.