Saturday, July 23, 2022

[SOLVED] How to delete every Pod in a Kubernetes namespace

Issue

Take this scenario:

src="https://i.stack.imgur.com/wSqHg.png" alt="enter image description here" />

I want to delete every running pod automatically using the Commandline without having to type kubectl delete pod <pod_name> -n <namespace> for each pod.


Solution

You can use awk to filter pod names based on their STATUS==RUNNING. Below code will delete all(in Running state) the pods from $NAMESPACE namespace.

 kubectl  get pod -n $NAMESPACE|awk '$3=="Running"{print $1}'

Example:

for pod in $(kubectl  get pod -n $NAMESPACE |awk '$3=="Running"{print $1}'); do
    kubectl delete pod -n $NAMESPACE $pod
done

OR

You may use jsonpath,

NAMESPACE=mynamespace
for pod in $(kubectl  get pod -n $NAMESPACE -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}{"\n"}'); do
    kubectl delete pod -n $NAMESPACE "$pod"
done

NOTE: Above code will cause deletion of all the pods in $NAMESPACE variable.

Example:

kubectl get pod -n mynamespace
NAME        READY   STATUS      RESTARTS   AGE
foo-mh6j7   0/1     Completed   0          5d3h
nginx       1/1     Running     2          7d10h
mongo       2/2     Running     12         57d
busybox     1/1     Running     187        61d

jsonpath query to print all pods in Running state:

kubectl  get pod -n mynamespace -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}{"\n"}'
nginx mongo busybox

Although, you have not asked for ready state, but following query can be used to list pods in ready state.

kubectl  get pod -n mynamespace -o jsonpath='{range .items[*]}{.status.containerStatuses[*].ready.true}{.metadata.name}{ "\n"}{end}'
foo-mh6j7
nginx
mongo
busybox

Similarly, this can be done via grep:

kubectl get pod -n $NAMESPACE |grep -P '\s+([1-9]+)\/\1\s+'

NOTE: Either of the solution will not prevent pods from getting respawned if they are created via replicaset or deployment or statefulset etc. This means, they will get deleted and respawned.



Answered By - P....
Answer Checked By - Marie Seifert (WPSolving Admin)