The selector option can help us to select a subset of pods with kubectl

2 min read | by Jordi Prats

On most kubectl command we will find the selector option for filtering pods based on it's labels. To use we just need to set the filter using the key=value format:

$ kubectl get pods -l "app=spin"
NAME                               READY   STATUS    RESTARTS   AGE
spin-clouddriver-9899c9b54-nbjp6   1/1     Running   0          29h
spin-deck-56ff48c587-lc75g         1/1     Running   0          29h
spin-echo-7ccf545b48-b5n9l         1/1     Running   0          29h
spin-front50-59bff89745-2f65h      1/1     Running   0          29h
spin-gate-644c968b68-2q8nj         1/1     Running   0          29h
spin-igor-6669794575-2cnb4         1/1     Running   0          29h
spin-orca-795789b678-nqrk7         1/1     Running   0          29h
spin-rosco-6c9879b69f-gdrfl        1/1     Running   0          29h

The selector filter besides supporting equality by using '=' and '==', it also supports checking for inequality using the '!=' operator:

$ kubectl get pods -l "app!=spin"
NAME                                          READY   STATUS      RESTARTS   AGE
spinnaker-install-using-hal-qfctn             0/1     Completed   0          2d7h
spinnaker-minio-4d667764d7-qg7r4              1/1     Running     0          2d23h
spinnaker-minio-97cc55ccd7-ztvc6              0/1     Pending     0          29h
spinnaker-spinnaker-cleanup-using-hal-nzzcp   0/1     Completed   0          3d
spinnaker-spinnaker-halyard-0                 1/1     Running     0          31h

We can also combine multiple lables like this:

$ kubectl get pods -l "app=spin,cluster=spin-clouddriver"
NAME                               READY   STATUS    RESTARTS   AGE
spin-clouddriver-9899c9b54-nbjp6   1/1     Running   0          29h

One of the commands that also supports this selector is kubectl top: Using the right selector we can locate which Pod for a given application is using the most CPU:

$ kubectl top pod --selector app=spin --sort-by cpu
NAME                               CPU(cores)   MEMORY(bytes)   
spin-clouddriver-9899c9b54-nbjp6   327m         958Mi           
spin-orca-795789b678-nqrk7         29m          420Mi           
spin-front50-59bff89745-2f65h      6m           391Mi           
spin-echo-7ccf545b48-b5n9l         5m           352Mi           
spin-gate-644c968b68-2q8nj         4m           367Mi           
spin-igor-6669794575-2cnb4         4m           336Mi           
spin-rosco-6c9879b69f-gdrfl        2m           293Mi           
spin-deck-56ff48c587-lc75g         1m           18Mi    

Posted on 10/03/2021

Categories