Search code examples
kuberneteskubectl

kubectl get pods: Field Selectors


I'm running this command:

# kubectl get pods --all-namespaces --field-selector=metadata.namespace!=kube-system,metadata.namespace!=monitoring,metadata.namespace!=rtf

Which gives me output like this:

NAMESPACE                        NAME              READY   STATUS    RESTARTS   AGE
123456-1234-1234-1234-123456789  some-app-123456   2/2     Running   0          10m
123456-1234-1234-1234-123456789  some-app-789112   1/2     Running   0          10m

I would like to be able to filter on the READY column, but I can't seem to find the right field-selector value.

Is this possible?

I've tried searching around for a list of available field-selectors, and haven't had any luck. It's possible that one doesn't exist.


Solution

  • I don't think kubectl get pods supports field selectors based on the READY column directly.

    But kubectl provides a method exporting the resource configuration (YAML) directly into JSON, -o json. Then, we can use jq to read, parse, and mutate K8s object results from kubectl.

    In your case, you could use a command like this to filter all pods (excluding the pods from namespaces kube-system, monitoring & rtf) not in ready state:

    kubectl get pods --all-namespaces --field-selector=metadata.namespace!=kube-system,metadata.namespace!=monitoring,metadata.namespace!=rtf -ojson | jq '.items[] | select(.status.containerStatuses[].ready==false) | .metadata.namespace + "/" + .metadata.name'
    

    and/or change ready=true to get the pods in ready state.

    Have a look at this article for many more such uses of jq with kubectl

    Hope it helps.