Labels and Selectors

(this post is part of the material I cover in my devops course)

Motivation

-Service deployments and batch processing pipelines are often multi-dimensional entities.

  • For example, you may have multiple micro-services per tier.

k8s labels

Labels

  • Labels are key/value pairs that are attached to objects, such as pods or deployments
  • Labels can be used to organize and to select subsets of objects.
    They are said to be "identifying", so you can base queries on them.
  • Non-identifying information should be recorded using annotations.
  • Labels can be attached to objects at creation time or later and can be changed
  • Each object can have a set of key/value labels defined
  • Each Key must be unique for a given object.
  • More info here
  • exanple:
1"metadata": {
2  "labels": {
3    "key1" : "value1",
4    "key2" : "value2"
5  }
6}

Label syntax

  • Labels are key/value pairs.
  • Valid label keys have two segments:
    • an optional prefix
    • a name separated by a slash (/) Example:
1app.example.com/name=my-app
  • Read more about label syntax here

Lable Selectors

  • Labels do not provide uniqueness.
  • Via a label selector, the client/user can identify a set of objects.
  • The label selector is the core grouping primitive in Kubernetes.
  • The API currently supports two types of selectors:
  • equality based example:
 1List only pods from app b:
 2    kubectl get pods --selector=app.k8s.io/name==appB
 3also with one equation mark:
 4    kubectl get pods --selector=app.k8s.io/name=appB
 5List only pods NOT from app b:
 6    kubectl get pods --selector=app.k8s.io/name!=appB
 7The , (comma operator) acts as a logical AND operation.
 8There is NO logical OR opration.
 9So:
10    kubectl get pods --selector=app.k8s.io/name==appB,app.k8s.io/release==3
  • set based example:
1Select all pods that are in the (appB, appC) set:
2    kubectl get pods --selector="app.k8s.io/name in (appB, appC)"
3Select all pods that are NOT in the (appB, appC) set:
4    kubectl get pods --selector="app.k8s.io/name notin (appB, appC)"
5Select all of these pods that HAVE the single "nice" label:
6    kubectl get pods --selector=nice
7Select all of these pods that DO NOT have the label "nice:
8    kubectl get pods --selector='!nice'
9    (notice we have used a bash-single-quotation mark)