Update: Managing Kubeconfig Files

June 6, 2021
Kubernetes Config Management kubeconfig

I while back I wrote about how I managed Kubeconfig files in my environment, in a easy-to-modify way.

I’ve changed my approach recently to make this easier to use; requiring a KUBECONFIG_MANUAL environment variable in order to avoid an explicitly-set KUBECONFIG being overwritten was error-prone and ergonomically poor.

I’ve recently decided to take a different approach, with the assumption that I will never explicitly set a KUBECONFIG environment variable using multiple files. As such, I can use the : character as a sentinel; if it is present in KUBECONFIG, it’s safe to override, and if not, we want to continue using the explicitly-set KUBECONFIG value.

This approach allows me to continue putting arbitrary config files into ~/.kube/configs, without losing the ability to explicitly set a kubeconfig path.

The new zsh code, which should be included in your ~/.zshrc file is:

function set-kubeconfig {
  # Sets the KUBECONFIG environment variable to a dynamic concatentation of everything
  # under ~/.kube/configs/*
  # Does NOT overwrite KUBECONFIG if it does not include a ":" (was most likely explicitly set)

  sentinel=":"
  if [ -z "$KUBECONFIG" ] || [[ $KUBECONFIG =~ $sentinel ]]; then
    # There is a colon in KUBECONFIG; it was automatically set
    if [ -d ~/.kube/configs ]; then
      export KUBECONFIG=~/.kube/config:$(find ~/.kube/configs -type f 2>/dev/null | xargs -I % echo -n "%:")
    fi
  fi
}

add-zsh-hook precmd set-kubeconfig

Hopefully this works out for you, or was at least helpful. If you have any questions, don’t hesitate to shoot me an email, or follow me on twitter @nrmitchi.