DEV Community

Julio
Julio

Posted on

Kubernetes (CKAD) - Pod Design - Understand how to use Labels, Selectors, and Annotations

Topic: Pod Design

Labels

Labels are key:pair values that can help you organize your resources. Any object in Kubernetes can have a label described.

You can also use labels to select a set of resources. For that you'll use a selector, which we'll see later on.

Example of a label:

apiVersion: v1
kind: Pod
metadata:
  name: onboarding-frontend
  namespace: my-application
  labels:
    service: onboarding
    tier: frontend
Enter fullscreen mode Exit fullscreen mode

Listing labels

$ kubectl get pods --show-labels
Enter fullscreen mode Exit fullscreen mode

Listing labels as columns

You can list labels as columns by using the -L (--label-columns) option of kubectl.

$ kubectl get pods -L service,tier
Enter fullscreen mode Exit fullscreen mode

Selectors

You can use selectors to filter a set of resources. For filtering based on labels, we can use the -l selector.

Select only the pods related to the onboarding service.

$ kubectl get pods -L service,tier -l 'service=onboarding'
Enter fullscreen mode Exit fullscreen mode

Select only the pods NOT related to the onboarding service.

$ kubectl get pods -L service,tier -l 'service!=onboarding'
Enter fullscreen mode Exit fullscreen mode

Select only the pods related to the onboarding service in the frontend tier

$ kubectl get pods -L service,tier -l 'service=onboarding,tier=frontend'
Enter fullscreen mode Exit fullscreen mode

Select all pods that are related to backend and frontend tiers.

$ kubectl get pods -L service,tier -l 'tier in (backend,frontend)'
Enter fullscreen mode Exit fullscreen mode

Annotations

Annotations allows you to store additional data for the object you're creating. Also a key:pair value but with more capacity to store longer strings, including JSON.

An annotation looks like:

apiVersion: v1
kind: Pod
metadata:
  name: onboarding-frontend
  namespace: my-application
  labels:
    service: onboarding
    tier: frontend
  annotations:
    Description: The frontend component of the onboarding service for my-application.
Enter fullscreen mode Exit fullscreen mode

List the annotations of a pod

$ kubectl describe pod onboarding-frontend | grep Annotations
Enter fullscreen mode Exit fullscreen mode

Annotations can be edited/removed/added.

Remove an annotation

$ kubectl annotate pod onboarding-frontend Description-
Enter fullscreen mode Exit fullscreen mode

The - after the annotation indicates that we want to removed it.

Add an annotation

$ kubectl annotate pod onboarding-frontend Description-
Enter fullscreen mode Exit fullscreen mode

The - after the annotation indicates that we want to remove it.

Official docs for further reference: Object Annotations

Top comments (0)