Skip to content

Instantly share code, notes, and snippets.

@deltakapa
Forked from negz/kubedump.sh
Created May 27, 2021 08:35
Show Gist options
  • Save deltakapa/6f1844232b5562266384d2e86faa314f to your computer and use it in GitHub Desktop.
Save deltakapa/6f1844232b5562266384d2e86faa314f to your computer and use it in GitHub Desktop.
Dump Kubernetes cluster resources as YAML
#!/usr/bin/env bash
set -e
CONTEXT="$1"
if [[ -z ${CONTEXT} ]]; then
echo "Usage: $0 KUBE-CONTEXT"
exit 1
fi
NAMESPACES=$(kubectl --context ${CONTEXT} get -o json namespaces|jq '.items[].metadata.name'|sed "s/\"//g")
RESOURCES="configmap secret daemonset deployment service hpa"
for ns in ${NAMESPACES};do
for resource in ${RESOURCES};do
rsrcs=$(kubectl --context ${CONTEXT} -n ${ns} get -o json ${resource}|jq '.items[].metadata.name'|sed "s/\"//g")
for r in ${rsrcs};do
dir="${CONTEXT}/${ns}/${resource}"
mkdir -p "${dir}"
kubectl --context ${CONTEXT} -n ${ns} get -o yaml ${resource} ${r} > "${dir}/${r}.yaml"
done
done
done
@deltakapa
Copy link
Author

Useful script

@deltakapa
Copy link
Author

deltakapa commented Sep 22, 2022

If you want all resources you could do:

RESOURCES=$(kubectl api-resources --namespaced -o name | tr "\n" " ")

and namespaces without jq:

kubectl get ns -o jsonpath="{.items[*].metadata.name}"

@deltakapa
Copy link
Author

deltakapa commented Sep 22, 2022

... | jq '.items[].metadata.name' | sed "s/\"//g"

# is equivalent to

... | jq -r '.items[].metadata.name'

@deltakapa
Copy link
Author

deltakapa commented Oct 21, 2022

One-line command to delete all k8s resources

all in kubernetes does not refers to every kubernetes object, such as admin level resources (limits, quota, policy, authorization rules). If you really want to make sure to delete eveything, it's better to delete the namespace and re-create it. Another way to do that is to use kubectl api-resources to get all resource types, as seen here

kubectl --context=$context-name -n $namespace delete "$(kubectl --context=$context-name -n $namespace api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e 's/,$//')" --all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment