Categories
Software development

Setting $KUBECONFIG

This should be simple. It’s an environment variable.

But, as with all things, it depends! What if you’re working with multiple clusters, or you setup and tear-down clusters often, or work with different tools that have certain expectations?

I’ve set it a few different ways:

Save cluster config file as $HOME/.kube/config

This works. But it feels messy!

I don’t like having to constantly overwrite the configuration file for my cluster’s source-of-truth.

Plus, kubectl (and maybe other programs?) overwrite this file when connections are made to clusters.

Set $KUBECONFIG path in ~/.profile

This works, too. It doesn’t scale well when you change clusters often or use a variety of tooling (due to tooling behaviors and expectations).

# Get the config file from the current folder or from home
export KUBECONFIG=kubeconfig:$HOME/.kube/config

If kubeconfig doesn’t exist in the current folder (maybe because the tool you’re using changed folders), $KUBECONFIG will resolve to to $HOME/.kube/config.

The problem is that $HOME/.kube/config isn’t necessarily my desired config…it represents what was last used.

Set $KUBECONFIG path in this session

I was using a script like this to initialize my k8s connection in a terminal. It helped ensure predictability (my machine’s state isn’t mutated), as I had to explicitly set the context given a script in that project folder.

#!/bin/sh
# call like this: source ./start.sh
#
# Do stuff we need done before beginning a development session
# Doesn't modfy the machine long-term
#
# read in the absolute path of the kubeconfig in my current directory
export KUBECONFIG=$(readlink kubeconfig -f)

Keep is simple, use kubectx

Now, I just use kubectx. Get it using arkade, and other handy tools and k8s applications.

Leave a Reply