Command to delete all pods in all kubernetes namespaces - kubernetes

Upon looking at the docs, there is an API call to delete a single pod, but is there a way to delete all pods in all namespaces?

There is no command to do exactly what you asked.
Here are some close matches.
Be careful before running any of these commands. Make sure you are connected to the right cluster, if you use multiple clusters. Consider running. kubectl config view first.
You can delete all the pods in a single namespace with this command:
kubectl delete --all pods --namespace=foo
You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace
kubectl delete --all deployments --namespace=foo
You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command:
kubectl delete --all namespaces
However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable.
This command will delete all the namespaces except kube-system, which might be useful:
for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
kubectl delete ns $each
done

kubectl delete daemonsets,replicasets,services,deployments,pods,rc,ingress --all --all-namespaces
to get rid of them pesky replication controllers too.

You can simply run
kubectl delete all --all --all-namespaces
The first all means the common resource kinds (pods, replicasets, deployments, ...)
kubectl get all == kubectl get pods,rs,deployments, ...
The second --all means to select all resources of the selected kinds
Note that all does not include:
non namespaced resourced (e.g., clusterrolebindings, clusterroles, ...)
configmaps
rolebindings
roles
secrets
...
In order to clean up perfectly,
you could use other tools (e.g., Helm, Kustomize, ...)
you could use a namespace.
you could use labels when you create resources.

You just need sed to do this:
kubectl get pods --no-headers=true --all-namespaces |sed -r 's/(\S+)\s+(\S+).*/kubectl --namespace \1 delete pod \2/e'
Explains:
use command kubectl get pods --all-namespaces to get the list of all pods in all namespaces.
use --no-headers=true option to hide the headers.
use s command of sed to fetch the first two words, which represent namespace and pod's name respectively, then assemble the delete command using them.
the final delete command is just like:
kubectl --namespace kube-system delete pod heapster-eq3yw.
use the e modifier of s command to execute the command assembled above, which will do the actual delete works.
To avoid delete pods in kube-system namespace, just need to add grep -v kube-system to exclude kube-system namespace before the sed command.

I tried commands from listed answers here but pods were stuck in terminating state.
I found below command to delete all pods from particular namespace if stuck in terminating state or you are not able to delete it then you can delete pods forcefully.
kubectl delete pods --all --grace-period=0 --force --namespace namespace
Hope it might be useful to someone.

K8s completely works on the fundamental of the namespace. if you like to release all the resource related to specified namespace.
you can use the below mentioned :
kubectl delete namespace k8sdemo-app

steps to delete pv:
delete all deployment and pods or resources related to that PV
kubectl delete --all deployment -n namespace
kubectl delete --all pod -n namespace
edit pv
kubectl edit pv pv_name -n namespace
remove kubernetes.io/pv-protection
delete pv
kubectl delete pv pv_name -n namespace

Delete all PODs in all Namespace only (restart deployment)
kubectl get pod -A -o yaml | kubectl delete -f -

You can use kubectl delete pods -l dev-lead!=carisa or what label you have.

Here is a one-liner that can be extended with grep to filter by name.
kubectl get pods -o jsonpath="{.items[*].metadata.name}" | \
tr " " "\n" | \
xargs -i -P 0 kubectl delete pods {}

One line command to delete all pods in all namespaces.
kubectl get ns -o=custom-columns=Namespace:.metadata.name --no-headers | xargs -n1 kubectl delete pods --all -n

kubectl delete po,ing,svc,pv,pvc,sc,ep,rc,deploy,replicaset,daemonset --all -A

If you already have pods which are recreated, think to delete all deployments first
kubectl delete -n *NAMESPACE deployment *DEPLOYMENT
Just replace the NAMSPACE and the DEPLOYMENT to corresponding ones, you can get all deployments information by the following command
kubectl get deployments --all-namespaces

Kubectl bulk (bulk-action on krew) plugin may be useful for you, it gives you bulk operations on selected resources. This is the command for deleting pods
' kubectl bulk pods -n namespace delete '
You could check details in this

I create a python code to delete all in namespace
delall.py
import json,sys,os;
obj=json.load(sys.stdin);
for item in obj["items"]:
os.system("kubectl delete " + item["kind"] + "/" +item["metadata"]["name"] + " -n yournamespace")
and then
kubectl get all -n kong -o json | python delall.py

If you have multiple pod which are crashing or error and you want to delete them
kubectl delete pods --all -n | gep

It was hinted at above, but I just thought I would helpfully point out that the shortcut for "--all-namespaces" is "-A" that's with a capital A. HTH somebody. I've opened a PR to have this helpful hint added to the official Kubernetes Cheat Sheet.

If you want to delete pods in all namespaces just to have them restarted and you are aware that some of them will be recreated, I like the following for loop:
for i in $(kubectl get pods -A | awk '{print $1}' | uniq | grep -V NAMESPACE); do kubectl delete --all pods -n $i; done

if you have hpa, then scale down.

Related

How to delete all the Terminated pods of a kubernetes cluster?

I know how to delete a specific pod:
kubectl -n <namespace> delete pod <pod-name>
Is there a way to delete all the Terminated pods once?
What does terminated pod mean? If you wish to delete finished pods of any jobs in the namespace then you can remove them with a single command:
kubectl -n <namespace> delete pods --field-selector=status.phase==Succeeded
Another approach in Kubernetes 1.23 onwards is to use Job's TTL controller feature:
spec:
ttlSecondsAfterFinished: 100
In your case Terminated status means your pods are in a failed state. To remove them just change the status.phase to Failed state (https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodStatus)
You can pipe 2 commands:
kubectl -n <namespace> get pods --field-selector=status.phase==Succeeded -o custom-columns=NAME:.metadata.name --no-headers | kubectl -n <namespace> delete pods
I don't think there is an 'exec' option to kubectl get (like the CLI tool 'find' for instance).
If the command fits your needs, you can always convert it to an alias or shell function

Kubernetes POD delete with Pattern Match or Wildcard

When I am using below it deletes the running POD after matching the pattern from commandline:
kubectl get pods -n bi-dev --no-headers=true | awk '/group-react/{print $1}' | xargs kubectl delete -n bi-dev pod
However when I am using this command as an alias in .bash_profile it doesn't execute .
This is how I defined it :
alias kdpgroup="kubectl get pods -n bi-dev --no-headers=true | awk '/group-react/{print $1}'| kubectl delete -n bi-dev pod"
when execute this as below I get below error in commandline:
~ $ kdpgroup
error: resource(s) were provided, but no name, label selector, or --all flag specified
When I define this in .bash_profile I get this :
~ $ . ./.bash_profile
-bash: alias: }| xargs kubectl delete -n bi-dev pod: not found
~ $
Am I missing something to delete POD using Pattern Match or with Wilcard ?
thanks
Am I missing something to delete POD using Pattern Match or with Wilcard?
When using Kubernetes it is more common to use labels and selectors. E.g. if you deployed an application, you usually set a label on the pods e.g. app=my-app and you can then get the pods with e.g. kubectl get pods -l app=my-app.
Using this aproach, it is easier to delete the pods you are interested in, with e.g.
kubectl delete pods -l app=my-app
or with namespaces
kubectl delete pods -l app=my-app -n default
See more on Kubernetes Labels and Selectors
Set-based selector
I have some pod's running in the name of "superset-react" and "superset-graphql" and I want to search my wildcard superset and delete both of them in one command
I suggest that those pods has labels app=something-react and app=something-graphql. If you want to classify those apps, e.g. if your "superset" varies, you could add a label app-type=react and app-type=graphql to all those type of apps.
Then you can delete pods for both app types with this command:
kubectl delete pods -l 'app-type in (react, graphql)'
As the question asks, this is about using a wild card. Let me give examples on using wild cards to delete pods.
Delete Pods which contain the word "application"
Replace <namespace> with the namespace you want to delete pods from.
kubectl get pods -n <namespace> --no-headers=true | awk '/application/{print $1}'| xargs kubectl delete -n <namespace> pod
This will give a response like the following. It will print out the deleted pods.
pod "sre-application-7fb4f5bff9-8crgx" deleted
pod "sre-application-7fb4f5bff9-ftzfd" deleted
pod "sre-application-7fb4f5bff9-rrkt2" deleted
Delete Pods which contain "application" or "service"
Replace <namespace> with the namespace you want to delete pods from.
kubectl get pods -n <namespace> --no-headers=true | awk '/application|service/{print $1}'| xargs kubectl delete -n <namespace> pod
This will give a response like the following. It will print out the deleted pods.
pod "sre-application-7fb4f5bff9-8crgx" deleted
pod "sre-application-7fb4f5bff9-ftzfd" deleted
pod "sre-service-7fb4f5bff9-rrkt2" deleted
You just need to escape the '$1' variable in the awk command:
alias kdpgroup="kubectl get pods -n bi-dev --no-headers=true | awk '/group-react/{print \$1}'| xargs kubectl delete -n bi-dev pod"
I know that escape is boring, and if you want to avoid it you can use as a function in you .bash_profile:
kdpgroup() {
kubectl get pods -n default --no-headers=true | awk '{print $1}' | xargs kubectl delete pod -n default
}
A robust way with variables, based on #keetSugathadasa answer:
ns="optional-namespace"
regex="pattern"
kubectl get pods ${ns:+ -n $ns} --no-headers | awk /${regex}/'{print $1}' \
| xargs kubectl delete ${ns:+ -n $ns} pod
using grep you can filter the keyword like this and delete matching pod name like this
kubectl get pods --no-headers=true | awk '{print $1}' | grep keyword | xargs kubectl delete pod

deleting all k8s objects by environment

what is the command to remove all objects using kubectl for a specific environment?
kubectl -n squad-mb get all
returns all environments for example, and in order to delete one environment I would like to know how to see it, and which command would be required to delete the specific environment (i.e. develop)
To delete all resources of a given namespaces use:
kubectl delete all --all -n {my-namespace}
Explanation:
Usage: kubectl delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)]) [options]
all: all resources types. If you want to delete only some resources you can do kubectl delete deployments,pods,replicasets,services --all
--all: delete all resources of a type (or all types if using all). Example: kubectl delete pods --all
-n: selects the desired namespace. If empty the command is valid for the default namespace of your context. You can select all namespaces with --all-namespaces
Just re-create the namespace:
kubectl delete ns squad-mb
kubectl create ns squad-mb
This will recursively delete everything inside.
kubectl -n namespace delete all pods -l env=dev

kubectl delete all resources except the kubernetes service

Is there a variant of kubectl delete all --all command or some other command to delete all resources except the kubernetes service?
I don't think there's a built-in command for it, which means you'll have to script your way out of it, something like this (add an if for the namespace you want to spare):
$ for ns in $(kubectl get ns --output=jsonpath={.items[*].metadata.name}); do kubectl delete ns/$ns; done;
Note: deleting a namespace deletes all its resources.

How to delete all resources from Kubernetes one time?

Include:
Daemon Sets
Deployments
Jobs
Pods
Replica Sets
Replication Controllers
Stateful Sets
Services
...
If has replicationcontroller, when delete some deployments they will regenerate. Is there a way to make kubenetes back to initialize status?
Method 1: To delete everything from the current namespace (which is normally the default namespace) using kubectl delete:
kubectl delete all --all
all refers to all resource types such as pods, deployments, services, etc. --all is used to delete every object of that resource type instead of specifying it using its name or label.
To delete everything from a certain namespace you use the -n flag:
kubectl delete all --all -n {namespace}
Method 2: You can also delete a namespace and re-create it. This will delete everything that belongs to it:
kubectl delete namespace {namespace}
kubectl create namespace {namespace}
Note (thanks #Marcus): 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 delete "$(kubectl api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e 's/,$//')" --all
Kubernetes Namespace would be the perfect options for you. You can easily create namespace resource.
kubectl create -f custom-namespace.yaml
$ apiVersion: v1
kind: Namespace
metadata:
name:custom-namespace
Now you can deploy all of the other resources(Deployment,ReplicaSet,Services etc) in that custom namespaces.
If you want to delete all of these resources, you just need to delete custom namespace. by deleting custom namespace, all of the other resources would be deleted. Without it, ReplicaSet might create new pods when existing pods are deleted.
To work with Namespace, you need to add --namespace flag to k8s commands.
For example:
kubectl create -f deployment.yaml --namespace=custom-namespace
you can list all the pods in custom-namespace.
kubectl get pods --namespace=custom-namespace
You can also delete Kubernetes resources with the help of labels attached to it. For example, suppose below label is attached to all resource
metadata:
name: label-demo
labels:
env: dev
app: nginx
now just execute the below commands
deleting resources using app label
$ kubectl delete pods,rs,deploy,svc,cm,ing -l app=nginx
deleting resources using envirnoment label
$ kubectl delete pods,rs,deploy,svc,cm,ing -l env=dev
can also try kubectl delete all --all --all-namespaces
all refers to all resources
--all refers to all resources, including uninitialized ones
--all-namespaces in all all namespaces
First backup your namespace resources and then delete all resources found with the get all command:
kubectl get all --namespace={your-namespace} -o yaml > {your-namespace}.yaml
kubectl delete -f {your-namespace}.yaml
Nevertheless, still some resources exists in your cluster.
Check with
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found --namespace {your-namespace}
If you really want to COMPLETELY delete your namespace, go ahead with:
kubectl delete namespace {your-namespace}
(tested with Client v1.23.1 and Server v1.22.3)
In case if you want to delete all K8S resources in the cluster. Then, easiest way would be to delete the entire namespace.
kubectl delete ns <name-space>
kubectl delete deploy,service,job,statefulset,pdb,networkpolicy,prometheusrule,cm,secret,ds -n namespace -l label
kubectl delete all --all
to delete all the resource in cluster.
after deleting all resources k8's will again relaunch the default services for cluster.