Can I get or delete a pod/resource by UID?

6.3k views Asked by At

The problem

It seems that deleting a pod by UID used to be possible, but has been removed (https://github.com/kubernetes/kubernetes/issues/40121).

It also seems one cannot get a pod by its resource either (https://github.com/kubernetes/kubernetes/issues/20572).

(Why did they remove deleting by UID, what is the use of the UID then?)

Why do I want to use UID in the first place, and not, say, name?

Because I need something like replicas and none of the controllers (like Job, Deployment etc) suit my case.
The good thing about UIDs is that kubernetes generates them -- I don't have to worry about differentiating the pods then, I just save the returned UID. So it would be great if I could use it later to delete that particular pod ("replica").

The question

Is it really not possible to use the UID to get/delete?

Is my only option then to take care of differentiating the pods myself (e.g. keep a counter or generate a unique id myself and set it as the name or label)?

3

There are 3 answers

0
Ian Lewis On

I assume you are writing a controller to manage a set of replicas using a TPR or CRD

The short answer is that you should not track pods by UID or name but by using a selector much like Deployments/ReplicaSets/Services do. If pods match that selector, you can check the Pod's metadata or Pod spec to see if it needs to be deleted for some reason.

0
Laz Rawski On

This works as a get by UID:

Use kubectl custom-columns

List all PodName along with its UID of a namespace:

$ kubectl get pods -n <namespace> -o custom-columns=PodName:.metadata.name,PodUID:.metadata.uid

source: How do I get the pod ID in Kubernetes?

Using awk and xargs and you can delete with custom-columns too.

0
Mithun On

Complementing to what Laz Rawski already said.

Command to get pod name for a given pod uid:

kubectl get pods -o custom-columns=PodName:.metadata.name,PodUID:.metadata.uid | grep <pod_uid> | awk '{print $1}'

Command to delete a pod for a given pod uid:

kubectl delete po $(kubectl get pods -o custom-columns=PodName:.metadata.name,PodUID:.metadata.uid | grep <pod_uid> | awk '{print $1}')

Disclaimer: Be careful with delete commands in prod env :)