How to make kubectl echo namespace when delete multiple pods with the same label

10/23/2019

I am writing a script to delete multiple pods across multiple namespaces. The process is to first mark all the pods to delete with a label, like kill=true, and then to delete them all.

Script as below:

kubectl label pods pod0 kill=true -n namespace0
kubectl label pods pod1 kill=true -n namespace0
kubectl label pods pod0 kill=true -n namespace1
kubectl label pods pod1 kill=true -n namespace1
......
kubectl delete pod -l kill=true --all-namespaces

When executing the last script, echo text is as below:

pod "pod0" deleted
pod "pod1" deleted
pod "pod0" deleted
pod "pod1" deleted
......

I'll insert timestamp for each line by script, as I need to know the exact time each one is killed. But the problem is I can't identify which pod is exactly killed as namespace isn't showed and there're multiple pods with the same name.

Thus my questions are as below:

  1. Is it possible to make kubectl show namespace in the echo text?
  2. If not, does kubectl guarantee the delete order in some way? Like sort by namespace, pod name?
-- Orpheus
kubectl
kubernetes

3 Answers

10/23/2019
  1. Is it possible to make kubectl show namespace in the echo text?

No, I think this is hardcoded in kubectl.

  1. If not, does kubectl guarantee the delete order in some way? Like sort by namespace, pod name?

It's possible that the pods within a namespace are deleted in alphabetical order, however, this is not guaranteed. It's also possible that the namespaces are iterated over in alphabetical order, however, this is not guaranteed as well. In short, it might work in a certain way in practice, but there are no guarantees that you can rely on.

Besides that, if you need to know the exact time that each pod is deleted, it's probably better to iterate through all the pods anyway and delete each one explicitly.

-- weibeld
Source: StackOverflow

10/23/2019

As @P Ekambaram mentioned, you can invoke pods delete action for every namespace entry, showing target namespace per each processing iteraction:

kubectl get ns | awk '{print $1}'| sed '1d'| while read -r namespace; do echo "Namespace: $namespace"; kubectl delete po -l kill=true -n $namespace; done

Hope you find it useful in yours researches.

-- mk_sta
Source: StackOverflow

10/23/2019

Why dont you write a small script to fetch all namespaces and iterate each namespace and delete the pods that has label kill=true.

you can echo the namespace at each iteration.

-- P Ekambaram
Source: StackOverflow