Skip to content

Instantly share code, notes, and snippets.

@mohatb
Created June 14, 2023 10:18
Show Gist options
  • Select an option

  • Save mohatb/d40e66bbc0043a4502464a0c20ef9660 to your computer and use it in GitHub Desktop.

Select an option

Save mohatb/d40e66bbc0043a4502464a0c20ef9660 to your computer and use it in GitHub Desktop.
merge two kubeconfig file with existing ~/.kube/config. this would be helpful for clusters created by Kubeadm which has similar fields in context
#!/bin/bash
# Input validation
if [ "$#" -ne 2 ]; then
echo "Usage: ./mergekubeconfig.sh <kubeconfig1> <kubeconfig2>"
exit 1
fi
# Function to generate a random string
generate_random_string() {
cat /dev/urandom | tr -dc 'a-z' | fold -w 6 | head -n 1
}
# File paths
kubeconfig1=$1
kubeconfig2=$2
temp_kubeconfig1=$(mktemp)
temp_kubeconfig2=$(mktemp)
# Backup and preprocess the kubeconfig files
cp "$kubeconfig1" "$temp_kubeconfig1"
cp "$kubeconfig2" "$temp_kubeconfig2"
random_suffix1=$(generate_random_string)
random_suffix2=$(generate_random_string)
# Rename clusters, contexts and users in the temp kubeconfig files
sed -i "s/name: \(.*\)/name: \1-$random_suffix1/g" "$temp_kubeconfig1"
sed -i "s/current-context: \(.*\)/current-context: \1-$random_suffix1/g" "$temp_kubeconfig1"
sed -i "s/cluster: \(.*\)/cluster: \1-$random_suffix1/g" "$temp_kubeconfig1"
sed -i "s/user: \(.*\)/user: \1-$random_suffix1/g" "$temp_kubeconfig1"
sed -i "s/name: \(.*\)/name: \1-$random_suffix2/g" "$temp_kubeconfig2"
sed -i "s/current-context: \(.*\)/current-context: \1-$random_suffix2/g" "$temp_kubeconfig2"
sed -i "s/cluster: \(.*\)/cluster: \1-$random_suffix2/g" "$temp_kubeconfig2"
sed -i "s/user: \(.*\)/user: \1-$random_suffix2/g" "$temp_kubeconfig2"
# Merge the kubeconfig files including the existing ~/.kube/config
KUBECONFIG="$temp_kubeconfig1:$temp_kubeconfig2:$HOME/.kube/config" kubectl config view --flatten > merged_kubeconfig
# Validate the merged kubeconfig file
if [ "$(cat merged_kubeconfig)" == "" ]; then
echo "Error: Merged kubeconfig is empty."
exit 1
fi
# Copy the merged kubeconfig file to the default location
cp merged_kubeconfig ~/.kube/config
# Clean up temp files
rm "$temp_kubeconfig1"
rm "$temp_kubeconfig2"
rm merged_kubeconfig
echo "Kubeconfig files successfully merged."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment