Count of nodes which do not have a label?

6/17/2019

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?

-- Att A
azure-kubernetes
google-kubernetes-engine
kubectl
kubernetes
kubernetes-pod

4 Answers

6/17/2019

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.

-- coderanger
Source: StackOverflow

6/17/2019

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
-- P Ekambaram
Source: StackOverflow

6/17/2019

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}}'
-- Adam Otto
Source: StackOverflow

6/17/2019

according to the official documentation I dont think there is a way of doing that, but you can do something like that with the negation of equality:

kubectl get nodes --selector=kubernetes.io/hostname!=node_host_name

basically you can select everything that doesn't have a particular label, you can also chain selectors

More reading: https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/

-- 4c74356b41
Source: StackOverflow