Video Thumbnail for Lesson
4.15: Labels and Annotations

Labels and Annotations

Labels and annotations are key-value metadata stored under the metadata section of most Kubernetes resources. They look similar but serve different purposes:

  • Labels are identifying information. They can be used to select a subset of resources and tie related objects together. For example, a Service uses label selectors to choose which Pods it routes traffic to. Labels are also convenient when filtering kubectl output.
  • Annotations are non-identifying metadata. They are commonly used by controllers or tooling to store configuration or historical data. Because annotations are arbitrary strings without schema validation, mistakes are easy to make, so double-check your annotation values.

Below is an excerpt from the example Service/Deployment.yaml in the course repo showing labels and annotations at multiple levels:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-minimal
  labels:
    foo: deployment-label
  annotations:
    bar: deployment-annotation
spec:
  replicas: 3
  selector:
    matchLabels:
      baz: pod-label
  template:
    metadata:
      labels:
        baz: pod-label
      annotations:
        bing: pod-annotation
    spec:
      containers:
        - name: nginx
          image: nginx:1.26.0

The accompanying Service.nginx-clusterip.yaml uses a label selector to target these pods and also contains its own labels and annotations.

Hands-On: Working with Labels and Annotations

We will deploy the sample from the 04-built-in-resource-types/Service directory and explore how labels and annotations behave.

1. Create a Namespace and Deploy the Example

# task 01-create-namespace
# - Create the namespace for these examples and set it as default.
cd 04-built-in-resource-types/Service
task 01-create-namespace

# task 02-apply-deployment
# - Deploy the example Deployment
task 02-apply-deployment

# task 03-apply-clusterip-service
# - Deploy the Service that selects pods via a label
task 03-apply-clusterip-service

2. Query Resources by Label

# Get pods with the "baz=pod-label" label
kubectl get pods -l baz=pod-label

# Show labels on the Service
kubectl get service nginx-clusterip --show-labels

3. Add and View Annotations

# Add a custom annotation to the Service
kubectl annotate service nginx-clusterip devops-directive.com/purpose=demo

# View annotations on the Service
kubectl describe service nginx-clusterip | grep -A2 Annotations

4. Clean Up

# task 06-delete-namespace
# - Delete the namespace to clean up
task 06-delete-namespace