Search code examples
kubectl

Using kubectl how do I select resource based on some criteria?


For example I can

$ kubectl get jobs --sort-by='.status.active'

which gives me a list of jobs. Their status could be 0 and 1, so first come jobs the with zeros, then ones. How do I select instead of sort? For example, display only the ones that have status equal to one.


Solution

  • Formatting output

    kubectl with --sort-by is more a way of formatting output similar to how you can choose what fields to show in the output.

    Filter using Field Selectors

    For some pre-defined fields, you can use field selectors to filter your output.

    Example

    kubectl get pods --field-selector status.phase=Running
    

    Labels and Selectors

    The most common and customizable way to select subsets of resources is to conciously add labels to your resources. E.g. labels for app-name or team-name.

    Then you can use selectors to e.g. select a subset of the resources using kubectl

    Example

    kubectl get pods -l environment=production,tier=frontend