Skip to content

Instantly share code, notes, and snippets.

@jim80net
Last active January 24, 2024 08:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jim80net/cd27985d72301a9344072b574142aa39 to your computer and use it in GitHub Desktop.
Save jim80net/cd27985d72301a9344072b574142aa39 to your computer and use it in GitHub Desktop.
A BASH script to export a kubernetes namespace.
# Prerequisites:
# [GNU Parallel](https://www.gnu.org/software/parallel/)
# [kubectl-neat](https://github.com/itaysk/kubectl-neat)
# [mikefarah/yq](https://github.com/mikefarah/yq)
#
# Usage:
# - Copy and paste the below into your active shell session. Alternatively, add to your shell initialization scripts.
# - kubectl_export <namespace>
# The folder structure will be created: <namespace>/<kind>/<resource_name>.yaml
#
# Inspired from https://www.studytonight.com/post/how-to-list-all-resources-in-a-kubernetes-namespace
function kubectl_export {
NAMESPACE=${1:?"Supply a namespace with this command"}
mkdir -p $NAMESPACE
kubectl api-resources --verbs=list --namespaced -o name | grep -v "events.events.k8s.io" | grep -v "events" | sort | uniq | parallel --tag --env NAMESPACE -- '\
kubectl get {} -n '$NAMESPACE' 2>&1 | grep -vq "No resources found in '$NAMESPACE' namespace" && \
mkdir -p '$NAMESPACE'/{} && \
kubectl neat get -- {} -n '$NAMESPACE' --ignore-not-found -o yaml | yq --split-exp "\"'$NAMESPACE'/{}/\" + .metadata.name" ".items[]"
'
}
export -f kubectl_export
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment