Skip to content

Instantly share code, notes, and snippets.

@luatnd
Created October 19, 2023 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luatnd/35ab09fda4047320943366eefe407952 to your computer and use it in GitHub Desktop.
Save luatnd/35ab09fda4047320943366eefe407952 to your computer and use it in GitHub Desktop.
merge kube config files tool to work with multiple k8s env
#!/bin/bash
# Usage: merge-kubeconfig [-h] [-r] [file1] [file2] [...] [file n]
# Options:
# -h, --help Show help
# -r, --reset override(replace) the current config rather than merge with it
#
# Eg:
#
# 1) Append
#
# merge-kubeconfig ~/.kube/k3s-fi.conf aws-k8s.config.yaml
#
# would append k3s-fi and aws-k8s config into current config, stored at ~/.kube/config
#
# 2) Replace
#
# merge-kubeconfig -r ~/.kube/k3s-fi.conf aws-k8s.config.yaml
#
# would empty the current config, then store k3s-fi and aws-k8s config into current config, stored at ~/.kube/config
# Initialize variables to store option values
show_help=0
do_reset=0
# Check the first argument
if [ $# -ge 1 ]; then
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
show_help=1
shift
elif [ "$1" == "-r" ] || [ "$1" == "--reset" ]; then
do_reset=1
shift
fi
fi
if [ "$show_help" -eq 1 ]; then
echo "Usage: merge-kubeconfig [-h] [-r] [file1] [file2] [...] [file n]"
echo "Options:"
echo " -h, --help Show help"
echo " -r, --reset override(replace) the current config rather than merge with it"
echo ""
echo "Eg:"
echo ""
echo " 1) Append"
echo " "
echo " merge-kubeconfig ~/.kube/k3s-fi.conf aws-k8s.conf"
echo " "
echo " would append k3s-fi and aws-k8s config into current config, stored at ~/.kube/config"
echo " "
echo " 2) Replace"
echo ""
echo " merge-kubeconfig -r ~/.kube/k3s-fi.conf aws-k8s.conf"
echo ""
echo " would empty the current config, then store k3s-fi and aws-k8s config into current config, stored at ~/.kube/config"
exit 0
fi
KUBECONFIG=""
for arg in "$@"; do
KUBECONFIG="${KUBECONFIG}:${arg}"
done
# Remove the fisrt `:` char
KUBECONFIG="${KUBECONFIG#:}"
if [ "$do_reset" -ne 1 ]; then
KUBECONFIG=~/.kube/config:$KUBECONFIG
fi
echo "---"
echo "KUBECONFIG=$KUBECONFIG"
echo "---"
export KUBECONFIG
kubectl config view --flatten > all-in-one-kubeconfig.yaml
mv all-in-one-kubeconfig.yaml ~/.kube/config
if [ "$do_reset" -eq 1 ]; then
echo "OK: replace current config with $@"
exit 0
else
echo "OK: merged current config with $@"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment