Last active
May 15, 2023 19:09
-
-
Save bartvdbraak/8a67cf30dbc2d0fab980512259c44c75 to your computer and use it in GitHub Desktop.
A way to quickly create a backup of your Kubernetes cluster with manifests for each resource per resource type per namespace (don't use this as a serious backup strategy)
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 | |
# Check if the backup directory is provided as an argument | |
if [ -z "$1" ]; then | |
echo "Usage: $0 <backup_directory>" | |
exit 1 | |
fi | |
# Get the backup directory from the command line argument | |
BACKUP_DIR="$1" | |
# Get the list of namespaces | |
NAMESPACE_LIST=$(kubectl get namespaces -o jsonpath='{.items[*].metadata.name}') | |
# Loop through each namespace | |
for NAMESPACE in $NAMESPACE_LIST; do | |
# Create a directory for the namespace | |
NAMESPACE_DIR="${BACKUP_DIR}/${NAMESPACE}" | |
mkdir -p "$NAMESPACE_DIR" | |
# Get the list of resources for the namespace | |
RESOURCE_LIST=$(kubectl api-resources --verbs=list --namespaced=true -o name | tr '\n' ' ') | |
# Loop through each resource | |
for RESOURCE in $RESOURCE_LIST; do | |
# Create a directory for the resource | |
RESOURCE_DIR="${NAMESPACE_DIR}/${RESOURCE}" | |
# Get the resources of the current type in the current namespace | |
RESOURCE_NAMES=$(kubectl get "$RESOURCE" -n "$NAMESPACE" -o jsonpath='{.items[*].metadata.name}') | |
# Check if there are resources of the current type | |
if [ -n "$RESOURCE_NAMES" ]; then | |
mkdir -p "$RESOURCE_DIR" | |
# Loop through each resource name | |
for RESOURCE_NAME in $RESOURCE_NAMES; do | |
# Get the resource in YAML format and save it to a file | |
kubectl get "$RESOURCE" "$RESOURCE_NAME" -n "$NAMESPACE" -o yaml > "${RESOURCE_DIR}/${RESOURCE_NAME}.yaml" | |
done | |
fi | |
done | |
done | |
echo "Cluster backup completed!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment