Kubernetes Core Concepts - Labels, Selectors and Annotations

Kubernetes Core Concepts - Labels, Selectors and Annotations

What are Labels in Kubernetes?

As per official documentation Labels are key/value pairs that are attached to objects, such as pods, services, deployments and replicasets etc.

When we categorize something based on their properties or characteristics and give them some name those are nothing but called as Labels.

labels.png

Example syntax to define Labels

Let us assume we have three sets of a same application running on three different environments such as- prod, dev and staging. In such cases we need to assign labels to those resources using their object configurations files.

# where environment is production
labels:
    environment: prod
    app: nginx
# where environment is development
labels:
    environment: dev
    app: nginx
# where environment is staging
labels:
    environment: staging
    app: nginx

We can attach Labels to objects during their creation time or can add or modify them later as well. Each Kubernetes object can have a set of key/value labels defined. Each label key must be unique for a given object.

Valid label values

Valid label keys have two segments: an optional prefix and name, separated by a slash (/).

  • Must be 63 characters or less (can be empty),
  • Unless empty, must begin and end with an alphanumeric character ([a-z0-9A-Z]),
  • Could contain dashes (-), underscores (_), dots (.), and alphanumerics between

What are Selectors in Kubernetes?

Selectors are used to filter out objects based on their assigned Labels. Labels and Selectors goes hand in hand.

For example Selectors will help us filter out objects like give all the application pods which are of type staging.

Example syntax to define Selectors

# where environment is production
selector:
    matchLabels:
      environment: prod
# where environment is development
selector:
    matchLabels:
      environment: dev
# where environment is staging
selector:
    matchLabels:
      environment: staging

Selector Types

Kubernetes supports two type of selectors −

  • Equality-based selectors
  • Set-based selectors

Equality-based Selectors ->

They allow filtering by key and value. Operators used as part of this are: =, ==, !=

Examples:

Here are few pods running in my environment. To view them by their Label name run the following command:

root@kube-master:~# kubectl get pods --show-labels

show-label-1.png

# this would return all resources with the `environment = prod` label
environment = prod

equity-1.png

# this would return all resources with key equal to `environment` and value distinct from  `staging`, and all resources with no label with the key `environment`
environment != staging

equity-2.png

Set-based Selectors->

Set-based selectors allow filtering of keys according to a set of values. Operators used as part of this are: in, notin, exists.

Examples:

To view all the pods with labels environment=prod and environment=staging.

kubectl get pods -l 'environment in (prod,staging)' --show-labels

To view all the pods with a key environment and value distinct from staging and all resources with no label with the key environment.

kubectl get pods -l 'environment notin (staging)' --show-labels

To view all the pods with a key environment and value distinct from staging.

kubectl get pods -l 'environment,environment notin (staging)' --show-labels

Labels selectors for Kubernetes objects will be defined in json or yaml files using maps, and only equality-based requirement selectors are supported.

matchExpressions Selector

matchExpressions label selector is more expressive in nature. It supports support set-based matching whereas matchLabels only supports exact matching. matchExpressionscan label selector can be used with or without the matchLabels selector.

# where environment is staging
selector:
    matchLabels:
      environment: staging
    matchExpressions:
      - {key: tier, operator: NotIn, values: [front-end]}

matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". matchExpressions is a list of pod selector requirements. Valid operators include In, NotIn, Exists, and DoesNotExist.

What are Annotations in Kubernetes?

When you want to attach arbitrary non-identifying metadata to Kubernetes objects which can be retrieved later by clients such as tools and libraries.

Example syntax to define Annotations

Annotations are also defined in a key/value map manner like Labels.

"metadata": {
  "annotations": {
    "key1" : "value1",
    "key2" : "value2"
  }
}

For example:

metadata:
  name: lco-annotations-demo
  annotations:
    imageregistry: "https://hub.docker.com/"

Create a Pod with Labels

Here also we have two methods for creating pods with Labels.

With kubectl command

Run the following command to create a pod with certain Label.

kubectl run nginx-prod --image=nginx -l environment=prod

-l, --labels='': Comma separated labels to apply to the pod(s). Will override previous values.

With yaml manifest file

Here is our yaml manifest file to create a demo pod.

root@kube-master:~/labels# cat lco-label-demo.yml
apiVersion: v1
kind: Pod
metadata:
  name: lco-label-demo-nginx
  labels:
    pod_type: demo
    app: nginx
spec:
  containers:
  - name: nginx
    image: nginx:1.14.2
    ports:
    - containerPort: 80

Run the following command to create the pod.

root@kube-master:~/labels# kubectl apply -f lco-label-demo.yml
pod/lco-label-demo-nginx created

Filter the pod using Label selectors where the label key defined as pod_type.

root@kube-master:~/labels# kubectl get pods -l 'pod_type = demo'
NAME                   READY   STATUS    RESTARTS   AGE
lco-label-demo-nginx   1/1     Running   0          112s

pod_type_demo.png

Remove a Label from Kubernetes object

To remove the label from any given Kubernetes resource you need to add - at the end of the Label key name.

For example we will remove pod_type label from pod lco-label-demo-nginx:

root@kube-master:~/labels# kubectl label pod lco-label-demo-nginx pod_type-

remove_label.png

That's all about Kubernetes Labels, Selectors and Annotations.

Hope you like the tutorial. Stay tuned and don't forget to provide your feedback in the response section.

Happy Learning!

Did you find this article valuable?

Support Learn Code Online by becoming a sponsor. Any amount is appreciated!