Count of nodes which do not have a label?

Viewed 6102

How do I use kubectl to get K8S nodes which do not have any labels? Also , how do I fetch K8S pods which do not have any labels?

7 Answers

For those who want to find resources without a specific label, no matter its value:

kubectl get ns --selector='!label_name'

You have to leverage kubectl -o flag and go-template output:

kubectl get nodes -o go-template='{{range .items }}{{if .metadata.labels }}{{else}}{{printf "%s\n" .metadata.name}}{{ end }}{{end}}

This command will show only nodes which do not have any labels. The same can be used for pods:

kubectl get pods --all-namespaces -o go-template='{{range .items }}{{if .metadata.labels }}{{else}}{{printf "%s\n" .metadata.name}}{{ end }}{{end}}'

The first answer works but you can also use the following

kubectl get nodes -l '!label_name'

There is no specific way to check for no labels in general without listing every possible label. You would have to do this client side.

here the client side jq query for it.

kubectl get nodes -o json| jq '.items[].metadata|select( has("labels") == false )|.name'

Here as bonus solution to find object (secret in this example) without any annotation nor labels

secretNoAnno=$(kubectl  get secret -o json| jq '.items[].metadata|select( has("annotations") == false )|.name') 
secretNoAnnoClean=$(echo "$secretNoAnno" | tr -d '"')
kubectl  get secret $secretNoAnnoClean -o json| jq '.items[].metadata|select( has("labels") == false )|.name'

there is no way to check the nodes/pods that dont have labels. Instead what you can do is check for nodes/pods for specific label

follow the below steps

add label mylabel=k8s

master $ kubectl get no
NAME      STATUS    ROLES     AGE       VERSION
master    Ready     master    51m       v1.11.3
node01    Ready     <none>    50m       v1.11.3
master $
master $
master $ kubectl label nodes node01 mylabel=k8s
node/node01 labeled
master $
master $ kubectl get no -L mylabel
NAME      STATUS    ROLES     AGE       VERSION   MYLABEL
master    Ready     master    52m       v1.11.3
node01    Ready     <none>    52m       v1.11.3   k8s

list nodes that has label mylabel=k8s

master $ kubectl get no -l mylabel=k8s
NAME      STATUS    ROLES     AGE       VERSION
node01    Ready     <none>    53m       v1.11.3
master $

list the nodes that doesnt have label mylabel=k8s

master $ kubectl get no -l mylabel!=k8s
NAME      STATUS    ROLES     AGE       VERSION
master    Ready     master    53m       v1.11.3
Related