Created
February 13, 2025 16:05
-
-
Save fredleger/ba984e29a3e90c09f8e0258f91c035d8 to your computer and use it in GitHub Desktop.
clean sa
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 | |
# Variables | |
NAMESPACE=$1 # The target namespace (passed as the first argument) | |
SECRET_NAME=$2 # The imagePullSecret to remove (passed as the second argument) | |
BACKUP_DIR="sa_backup" # Base directory to store backups | |
DRY_RUN=$3 # Enable dry-run mode (passed as the third argument: "dry-run") | |
# Function to check prerequisites | |
function check_prerequisites() { | |
if ! command -v kubectl &> /dev/null; then | |
echo "โ kubectl not found. Please install it and configure your context." | |
exit 1 | |
fi | |
if [[ -z "$NAMESPACE" || -z "$SECRET_NAME" ]]; then | |
echo "Usage: $0 <namespace> <imagePullSecretName> [dry-run]" | |
exit 1 | |
fi | |
} | |
# Backup ServiceAccount | |
function backup_sa() { | |
local sa_name=$1 | |
local ns_backup_dir="$BACKUP_DIR/$NAMESPACE" | |
mkdir -p "$ns_backup_dir" | |
echo "๐น Backing up ServiceAccount '$sa_name' in namespace '$NAMESPACE'..." | |
[[ "$DRY_RUN" == "dry-run" ]] && echo "DRY-RUN: Would back up '$sa_name' to '$ns_backup_dir/$sa_name.json'" && return | |
kubectl get sa "$sa_name" -n "$NAMESPACE" -o json > "$ns_backup_dir/$sa_name.json" | |
} | |
# Patch ServiceAccount | |
function patch_sa() { | |
local sa_name=$1 | |
echo "๐น Patching ServiceAccount '$sa_name' to remove imagePullSecret '$SECRET_NAME'..." | |
# JSON Patch to remove the specific imagePullSecret | |
PATCH="[{\"op\": \"remove\", \"path\": \"/imagePullSecrets/$(kubectl get sa $sa_name -n $NAMESPACE -o json | jq '.imagePullSecrets | map(.name == "'"$SECRET_NAME"'") | index(true)')\"}]" | |
if [[ "$DRY_RUN" == "dry-run" ]]; then | |
echo "DRY-RUN: Would patch '$sa_name' with: $PATCH" | |
else | |
kubectl patch sa "$sa_name" -n "$NAMESPACE" --type json -p "$PATCH" 2>/dev/null || { | |
echo "โ ๏ธ Failed to patch $sa_name. It might not have the imagePullSecret '$SECRET_NAME'." | |
} | |
fi | |
} | |
# Main function | |
function main() { | |
check_prerequisites | |
# Get list of all ServiceAccounts in the namespace | |
echo "๐ Fetching ServiceAccounts in namespace '$NAMESPACE'..." | |
SA_LIST=$(kubectl get sa -n "$NAMESPACE" -o jsonpath='{.items[*].metadata.name}') | |
# Loop through each SA and process it | |
for sa in $SA_LIST; do | |
echo "Processing ServiceAccount: $sa" | |
backup_sa "$sa" | |
patch_sa "$sa" | |
done | |
echo "โ Operation completed! Backups are stored in '$BACKUP_DIR/$NAMESPACE'." | |
} | |
# Execute the main function | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment