Managing multiple Kubernetes resources by label


Kubernetes labels are super useful. If you aren’t familiar with them, a label is a key/value pair assigned in the metadata section (either metadata.labels, or spec.template.metadata.labels) of a deployment manifest. The following example assigns three key/value labels to a deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
    group: dse
    env: staging

$ kubectl get deploy nginx -o json | jq '.metadata.labels'

{
  "app": "nginx",
  "env": "staging",
  "group": "dse"
}

Labels get super useful when you need to apply an action to multiple resources. Actions can include get:

$ kubectl get po -l app=nginx

NAME                    READY   STATUS    RESTARTS   AGE
nginx-f89759699-65ngc   1/1     Running   0          114s
nginx-f89759699-98qdd   1/1     Running   0          114s
nginx-f89759699-b7mbs   1/1     Running   0          114s
nginx-f89759699-g2xcq   1/1     Running   0          114s
nginx-f89759699-gbjb9   1/1     Running   0          114s
nginx-f89759699-j9cnx   1/1     Running   0          114s
nginx-f89759699-mpqjl   1/1     Running   0          114s
nginx-f89759699-r9csq   1/1     Running   0          114s
nginx-f89759699-t44fq   1/1     Running   0          114s
nginx-f89759699-vppwf   1/1     Running   0          114s

Which will get all pods with the label “app=nginx”. You can also use this with actions like “delete”, which will trigger the deletion of any pod matching the label passed to the “-l” option:

$ kubectl delete po -l app=nginx

pod "nginx-f89759699-65ngc" deleted
pod "nginx-f89759699-98qdd" deleted
pod "nginx-f89759699-b7mbs" deleted
pod "nginx-f89759699-g2xcq" deleted
pod "nginx-f89759699-gbjb9" deleted
pod "nginx-f89759699-j9cnx" deleted
pod "nginx-f89759699-mpqjl" deleted
pod "nginx-f89759699-r9csq" deleted
pod "nginx-f89759699-t44fq" deleted
pod "nginx-f89759699-vppwf" deleted

Additionally, this can also be used with actions like “drain”, “taint” and “untaint”. If you are working with hundreds of nodes, or thousands of pods, this will save you a ton of time when debugging and managing your infrastructure!

This article was posted by on 2020-05-14 00:00:00 -0500 -0500