Last active
January 14, 2025 04:40
-
-
Save thuanpham582002/374e5bde61a3f01e20d103cd546a15ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: