Skip to content

Instantly share code, notes, and snippets.

@zburgermeiszter
Last active April 19, 2024 21:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zburgermeiszter/52806b02465e35f6111638b3f8bbf171 to your computer and use it in GitHub Desktop.
Save zburgermeiszter/52806b02465e35f6111638b3f8bbf171 to your computer and use it in GitHub Desktop.
Export all resources from Kubernetes (k8s) clusters. Resources are exported to separate folders and files by namespace and API name.
#!/bin/bash
backup_folder="kubernetes_backup"
# Create a directory to store the backup
mkdir -p $backup_folder
# Get a list of all resource resources, including both namespaced and non-namespaced resources
resources=$(kubectl api-resources --verbs=list -o name)
# Get a list of all namespaces
namespaces=$(kubectl get namespaces -o=jsonpath='{.items[*].metadata.name}')
# Retrieve non-namespaced resources
for resource in $resources; do
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting: $resource"
# Check if the resource is namespaced
if [ $(kubectl get $resource -o jsonpath='{.items[*].metadata.namespace}' | wc -w) -gt 0 ]; then # if namespaced
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting (namespaced): $resource"
for namespace in $namespaces; do
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting: $namespace/$resource"
if [ $(kubectl get $resource --namespace=$namespace -o jsonpath='{.items[*].metadata.name}' | wc -w) -gt 0 ]; then
mkdir -p $backup_folder/$namespace/$resource
# Write each item to its own file
for item in $(kubectl get $resource --namespace=$namespace -o jsonpath='{.items[*].metadata.name}'); do
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting: $namespace/$resource/$item"
kubectl get $resource $item --namespace=$namespace -o yaml >$backup_folder/$namespace/$resource/$item.yaml
done
fi
done
else # if not namespaced
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting (non-namespaced): $resource"
if [ $(kubectl get $resource -o jsonpath='{.items[*].metadata.name}' | wc -w) -gt 0 ]; then
# kubectl get $resource -o yaml >$backup_folder/${resource}.yaml
mkdir -p $backup_folder/non-namespaced/$resource
for item in $(kubectl get $resource -o jsonpath='{.items[*].metadata.name}'); do
echo "$(date +"%Y-%m-%d %H:%M:%S") - Exporting: $resource/$item"
kubectl get $resource $item -o yaml >$backup_folder/non-namespaced/$resource/$item.yaml
done
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment