Kubernetes – Labels, Selectors & Annotations
Labels
Labels are key/value pairs that are used to add metadata to Kubernetes objects. They can be used to select and group subsets of objects in the cluster. Labels are added to an object in the metadata.labels
section of the object descriptor as shown in the two Pod
definitions below.
apiVersion: v1 kind: Pod metadata: name: dev-pod labels: app: my-service environment: dev spec: containers: - name: nginx-container image: nginx imagePullPolicy: Always
apiVersion: v1 kind: Pod metadata: name: prod-pod labels: app: my-service environment: prod spec: containers: - name: nginx-container image: nginx imagePullPolicy: Always
After creating the above Pod
s run kubectl get pods --show-labels
to see the labels associated with each.
Selectors
Selectors are used to identify and select a set of objects based on their labels.
Equality & Inequality Selectors
Running kubectl get pods -l environment=dev
will output Pods where label environment
is dev
.
You can also use negation to list Pods not matching a selector. For example kubectl get pods -l environment!=dev
will output Pods where label environment
is not dev
.
Set Based Selectors
You can use a Set based selector to find Pods matching a group of values. For example kubectl get pods -l' environment in (dev,prod)' --show-labels
will output Pods where label environment
is dev
or prod
.
Chained Selectors
Chained selectors allow you to aggregate the results of multiple selectors using a comma separated list like this
kubectl get pods -l app=my-service,environment=dev --show-labels
.
Annotations
Annotations are similar to selectors in that they allow you to associate metadata with a Kubernetes object. Unlike Selectors though, annotations can’t be used to select or group objects. Some sample use cases for annotations are specifying contact info for the object maintainer or the Git commit hash of the object.
Annotations are added to an object in the metadata.annotations
section of the object descriptor and are visible in the Pod
metadata when you run a describe
like this kubectl describe pod annotation-pod
.
The sample code for these notes is available in Github.
Leave A Comment