Managing Multiple Kube Config Files

2024-02-22 (updated 2025-10-25)
Notes | 1 min read
#k8s #productivity #scripting

This is a simple script that takes multiple kube config files and deeply merges them into one.

I’ve since switched to [[kubeswitch]], which works much cleaner than this home-grown script.

Simply place your kube config files in ~/.kube/configs/ and run the script to replace ~/.kube/config with the merged result of the config folder.

#!/bin/bash
# Merge multiple kube config files into one for use with kubectl

set -e

CONFIGS_DIR=~/.kube/configs
MERGE_FILE=~/.kube/configs/_merged
KUBE_CONFIG=~/.kube/config

# Merge all configs in this folder into a config file for use by kubectl
yq eval-all '. as $item ireduce ({}; . *+ $item )' $CONFIGS_DIR/*.yaml > $MERGE_FILE

# Backup current config
printf -v datestamp '%(%Y-%m-%d-%H-%M-%S)T'
cp $KUBE_CONFIG "$KUBE_CONFIG.$datestamp"

# Overwrite the old config
cp $MERGE_FILE $KUBE_CONFIG