Created
July 29, 2025 13:30
-
-
Save chermed/7ce799a8f89efb998c81a3425bdad389 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| set -euo pipefail | |
| # Set backup output directory | |
| TIMESTAMP=$(date +%Y%m%d-%H%M%S) | |
| BACKUP_DIR="./k8s-backup-$TIMESTAMP" | |
| GLOBAL_DIR="$BACKUP_DIR/__global" | |
| mkdir -p "$BACKUP_DIR" | |
| mkdir -p "$GLOBAL_DIR" | |
| echo "π Starting Kubernetes backup to $BACKUP_DIR..." | |
| ######################################## | |
| # Backup namespaced resources by namespace | |
| ######################################## | |
| namespaces=$(kubectl get ns -o jsonpath='{.items[*].metadata.name}') | |
| namespaced_resources=$(kubectl api-resources --namespaced=true --verbs=list -o name) | |
| for ns in $namespaces; do | |
| echo "π Backing up namespace: $ns" | |
| NS_DIR="$BACKUP_DIR/$ns" | |
| mkdir -p "$NS_DIR" | |
| for resource in $namespaced_resources; do | |
| items=$(kubectl get "$resource" -n "$ns" --no-headers --ignore-not-found -o custom-columns=NAME:.metadata.name || true) | |
| for item in $items; do | |
| echo " πΉ $resource/$item" | |
| kubectl get "$resource" "$item" -n "$ns" -o yaml > "$NS_DIR/${resource//\//_}--${item}.yaml" | |
| done | |
| done | |
| done | |
| ######################################## | |
| # Backup cluster-wide (non-namespaced) resources | |
| ######################################## | |
| global_resources=$(kubectl api-resources --namespaced=false --verbs=list -o name) | |
| echo "π Backing up cluster-wide resources..." | |
| for resource in $global_resources; do | |
| items=$(kubectl get "$resource" --no-headers --ignore-not-found -o custom-columns=NAME:.metadata.name || true) | |
| for item in $items; do | |
| echo " π $resource/$item" | |
| kubectl get "$resource" "$item" -o yaml > "$GLOBAL_DIR/${resource//\//_}--${item}.yaml" | |
| done | |
| done | |
| echo "β Kubernetes cluster backup completed: $BACKUP_DIR" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment