• Recent blogs

    How do we list all pods controlled by deployments?

     How do Pods & Deployments relate?

    There's a label in the pod for the selector in the deployment. That's how a deployment manages its pods. For example for the label or selector "app=http" you can do something like that this and avoid using grep and listing all the pods (this becomes useful as your number of pods becomes very large)


    .spec.selector is a required field that specifies a label selector for the Pods targeted by this Deployment.

    .spec.selector must match .spec.template.metadata.labels, or it will be rejected by the API.

    A Deployment may terminate Pods whose labels match the selector if their template is different from .spec.template

    If you have multiple controllers that have overlapping selectors, the controllers will fight with each other and won't behave correctly.

    Here are some examples command line:

    # single label
    kubectl get pods -l=app=http
    kubectl get pods --selector=app=http
    # multiple labels
    kubectl get pods --selector key1=value1,key2=value2

    You can use the --custom-columns to find out which pods are controlled, and which kind of controller is the owner. Example:

    bash-3.2$ kubectl get pods --all-namespaces -o custom-columns=NAME:.metadata.name,CONTROLLER:.metadata.ownerReferences[].kind,NAMESPACE:.metadata.namespace


    % kubectl get pods --all-namespaces -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,CONTROLLER:.metadata.ownerReferences\[\].kind


    Remember that Deployments automatically create ReplicaSets and rely on them to manage a set of pods and its desired state/replicas. So you can just filter them:

    $ kubectl get pods --all-namespaces -o json | jq -r '.items | map(select(.metadata.ownerReferences[]?.kind == "ReplicaSet" ) | .metadata.name) | .[]'


    If you are using MAC OS, Then you'll face this error:
    zsh: no matches found: custom-columns=NAME:.metadata.name,CONTROLLER:.metadata.ownerReferences[].kind,NAMESPACE:.metadata.namespace

    To solve this, you need to use an escape character.


    % kubectl get pods --all-namespaces -o custom-columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace,CONTROLLER:.metadata.ownerReferences\[\].kind

    Please share. “Share your knowledge. It is a way to achieve immortality.”

    No comments