Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Update kubectl config file whenever new file is added to ~/.kube/conf.d
#! /bin/bash
# Or to can be added to ~/.bashrc
function update_kubeconfigs() {
# All individual config files should reside ~/.kube/config.d/
if [ ! -d "$HOME/.kube/config.d" ]; then mkdir $HOME/.kube/config.d -p -v ; fi
# Will run only if there is a new file in the config directory
local new_files=$(find $HOME/.kube/config.d/ -newer $HOME/.kube/config -type f | wc -l)
if [[ $new_files -ne "0" ]]; then
local current_context=$(kubectl config current-context) # Save last context
local kubeconfigfile="$HOME/.kube/config" # New config file
cp -a $kubeconfigfile "${kubeconfigfile}_$(date +"%Y%m%d%H%M%S")" # Backup
local kubeconfig_files="$kubeconfigfile:$(ls $HOME/.kube/config.d/* | tr '\n' ':')"
KUBECONFIG=$kubeconfig_files kubectl config view --merge --flatten > "$HOME/.kube/tmp"
#install -m 600 "$HOME/.kube/tmp" $kubeconfigfile
mv "$HOME/.kube/tmp" $kubeconfigfile && chmod 600 $kubeconfigfile
export KUBECONFIG=$kubeconfigfile
kubectl config use-context $current_context --namespace=default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment