What is the recommended way to get the pods of a Kubernetes deployment?

5/20/2018

Especially considering all the asynchronous procedures involved with creating and updating a deployment, I find it difficult to reliably find the current pods associated with the current version of a given deployment.

Currently, I do:

  1. Add unique labels to the deployment's template.
  2. Get the revision number of the deployment.
  3. Get all replica sets with the labels.
  4. Filter them further to find the one with the correct revision number.
  5. Extract the pod template hash from the replica set.
  6. Get all pods with the labels plus the pod template hash.

This is awkward and complex. Besides, I am not sure that (4) and (6) are guaranteed to yield only the wanted objects. But I cannot filter by ownerReferences, can I?

Is there a more robust and simpler way?

-- Torsten Bronger
kubernetes
kubernetes-deployment
kubernetes-pod

1 Answer

5/21/2018

When you create Deployment, it creates ReplicaSet, which creates Pods.

ReplicaSet contains "ownerReferences" path which includes the name and the UID of the parent deployment.

Pods contain the same path with the link to the parent ReplicaSet.

Here is an example of ReplicaSet info:

# kubectl get rs nginx-deployment-569477d6d8 -o yaml
apiVersion: extensions/v1beta1
kind: ReplicaSet
...
name: nginx-deployment-569477d6d8
namespace: default
ownerReferences:
- apiVersion: extensions/v1beta1
  blockOwnerDeletion: true
  controller: true
  kind: Deployment
  name: nginx-deployment
  uid: acf5fe8a-5d0e-11e8-b14f-42010a8000fc

...

-- Anton Kostenko
Source: StackOverflow