Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Kubernetes: Delete all objects in the namespace
kubectl delete "$(kubectl api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e 's/,$//')" --all
#!/usr/bin/env bash
#
# kubectl-delete_all is a utility to delete all objects in the namespace.
[[ -n "$DEBUG" ]] && set -x
set -eou pipefail
exec kubectl delete "$(kubectl api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e 's/,$//')" --all "$@"
@superbrothers
Copy link
Author

superbrothers commented Jan 17, 2019

You can install kubectl-delete_all plugin in the following steps:

$ wget https://gist.githubusercontent.com/superbrothers/b428cd021e002f355ffd6dd421b75f70/raw/36200fe7db03360c40b6c97c480d91688db7f2a4/kubectl-delete_all
$ chmod +x kubectl-delete_all
$ mkdir -p ~/bin
$ export PATH="$HOME/bin:$PATH"
$ mv kubectl-delete_all ~/bin
$ kubectl delete-all -n default
endpoints "kubernetes" deleted
secret "default-token-cx4p7" deleted
serviceaccount "default" deleted
service "kubernetes" deleted

@pranay-tibco
Copy link

pranay-tibco commented Sep 29, 2021

This is useful - but making it easy to copy and paste - this uses fake namespace just for testing
You can copy and paste below lines your shell to try it out

wget https://gist.githubusercontent.com/superbrothers/b428cd021e002f355ffd6dd421b75f70/raw/36200fe7db03360c40b6c97c480d91688db7f2a4/kubectl-delete_all
chmod +x kubectl-delete_all
mkdir ~/bin || { echo "This might fail - that's fine"; } 
export PATH="$HOME/bin:$PATH"
mv kubectl-delete_all ~/bin
kubectl delete-all -n fake

@superbrothers
Copy link
Author

superbrothers commented Sep 30, 2021

@pranay-tibco Thanks for your comment. I've changed to use mkdir -p😊

@scheung38
Copy link

scheung38 commented Jan 20, 2022

Hi @superbrothers: Does kubectl delete namespace jenkins for example does not delete all objects in jenkins namespace in this context?

@superbrothers
Copy link
Author

superbrothers commented Jan 21, 2022

@scheung38 I did not understand your question. For example, the following command will delete all namespaced objects in jenkins namespace.

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

@psdally
Copy link

psdally commented Mar 17, 2022

@scheung38's question, I think, is "Why bother with this plugin? Why not just delete the namespace itself, thereby implicitly deleting all of the objects within it?"

Depending on your roles and rolebindings, you might not have access to delete non-Namespaced objects (which a Namespace is), or re-create them. Sometimes Namespace deletions also get "stuck" on finalizers. So, deleting the contents of the Namespace without deleting the Namespace itself certainly is useful in some contexts.

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