K8s Labels & Annotations

Sandeep Baldawa
ITNEXT
Published in
2 min readApr 16, 2021

--

We saw an introduction to labels in our article here. In this article, let’s try to understand the differences between labels and annotation & when to use one over another.

Let’s quickly summarize what we learned about labels

Why use Labels in K8s?

Labels allow K8s to group a set of related resources(example:- all prod resources). Selectors are used to querying those labels(example:- get me all prod resources). Official Docs here. Something to note, at the time of writing of this article, below are the restrictions on how a label must be defined in K8s

Valid label value:

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

Why would we need something called annotations now in K8s?

Annotations are used to add metadata for K8 objects, which K8s do not care about. Therefore, the keys & values used in annotation have no restrictions(unlike labels).

But why can’t we use labels instead of annotations, why add more complexity?

If one would want to add information for other humans about a given resource and would not like K8s to care about it, annotations work best. Plus, annotations are pretty flexible and can include anything without restrictions.

Below is an example of annotations

apiVersion: v1
kind: Pod
metadata:
name: annotations-demo
annotations:
why_use_this_demo: "It's to learn about annotations"
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
selector:
env: prod

Let’s try to annotate a pod

We first create a pod called pod10.

MyK8sInstance> kubectl run pod10 --image=nginx:alpine --restart=Never
pod/pod10 created

Then annotate it with msg, note it has to be a key/value pair

MyK8sInstance> kubectl get po | grep -i pod10
pod10 1/1 Running 0 22s
MyK8sInstance> kubectl annotate pod pod10 msg="I like pod10"
pod/pod10 annotated

To validate the annotation worked

MyK8sInstance> kubectl get pod pod10 -o yaml | grep  msg
msg: I like pod10

That’s all for now, till next time ciao!

--

--

whoami >> Slack, Prev — Springpath (Acquired by Cisco), VMware, Backend Engineer, Build & Release, Infra, Devops & Cybersecurity Enthusiast