Skip to content

Instantly share code, notes, and snippets.

@thuanpham582002
Last active January 14, 2025 04:40
Show Gist options
  • Save thuanpham582002/374e5bde61a3f01e20d103cd546a15ec to your computer and use it in GitHub Desktop.
Save thuanpham582002/374e5bde61a3f01e20d103cd546a15ec to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script merges multiple kubeconfig files into one while preserving existing configurations
set -e
# Step 1: Create backup directory if it doesn't exist
BACKUP_DIR="$HOME/.kube/backups"
mkdir -p "$BACKUP_DIR"
# Step 2: Create timestamped backup of current config
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/config_backup_$TIMESTAMP"
if [ -f "$HOME/.kube/config" ]; then
cp "$HOME/.kube/config" "$BACKUP_FILE"
echo "Backup created at: $BACKUP_FILE"
fi
# Step 3: Set the KUBECONFIG environment variable
if [ "$#" -gt 0 ]; then
# If files are provided as arguments, use them
KUBECONFIG_FILES="$HOME/.kube/config"
for file in "$@"; do
if [ -f "$file" ]; then
KUBECONFIG_FILES="$KUBECONFIG_FILES:$file"
else
echo "Warning: File $file not found, skipping..."
fi
done
export KUBECONFIG="$KUBECONFIG_FILES"
else
# Find all yaml/yml files in current directory
KUBECONFIG_FILES="$HOME/.kube/config"
for file in *.yaml *.yml; do
if [ -f "$file" ]; then
KUBECONFIG_FILES="$KUBECONFIG_FILES:$PWD/$file"
fi
done
export KUBECONFIG="$KUBECONFIG_FILES"
fi
# Step 4: Create temporary file for merged config
TEMP_CONFIG=$(mktemp)
# Step 5: Merge configurations
kubectl config view --flatten > "$TEMP_CONFIG"
# Step 6: Verify the merged config is valid
if kubectl --kubeconfig="$TEMP_CONFIG" config get-contexts > /dev/null 2>&1; then
# If verification successful, move to final location
mv "$TEMP_CONFIG" "$HOME/.kube/config"
chmod 600 "$HOME/.kube/config"
echo "Successfully merged kubeconfig files"
echo "Original config backed up at: $BACKUP_FILE"
echo "Available clusters:"
kubectl config get-clusters
else
echo "Error: Generated config is invalid. Keeping original config."
rm "$TEMP_CONFIG"
exit 1
fi
@thuanpham582002
Copy link
Author

thuanpham582002 commented Nov 29, 2024

Usage:

curl -sfL https://gist.githubusercontent.com/thuanpham582002/374e5bde61a3f01e20d103cd546a15ec/raw/4c98c6e3b9d5e57af3f8e2c6aa4099b59e5161b4/script%2520merge%2520kube%2520config | bash -s $YOUR_CONFIG_NEED_MERGE_HERE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment