Labels, Selectors & Annotations
A cluster can hold thousands of objects. Labels are how you organise them, and selectors are how Kubernetes objects find each other. A Service finds its Pods by label; a Deployment finds the Pods it owns by label; kubectl get -l filters by label.
Labels
Labels are key/value strings in metadata.labels:
metadata:
name: api-7d9f-x2k4p
labels:
app.kubernetes.io/name: api
app.kubernetes.io/part-of: shop
tier: backend
environment: production
track: stable- Keys have an optional prefix (
app.kubernetes.io/) and a name of up to 63 characters. - Values are up to 63 characters (letters, digits,
-,_,.), or empty. - Labels are meant to be identifying: things you want to select by.
The app.kubernetes.io/* labels (name, instance, version, component, part-of, managed-by) are a recommended convention that tools like Helm and dashboards understand.
Selectors
There are two kinds of selector requirement:
| Kind | Syntax (kubectl) | YAML (matchLabels / matchExpressions) |
|---|---|---|
| Equality | tier=backend, tier!=backend |
matchLabels: {tier: backend} |
| Set-based | env in (prod,staging), env notin (dev), track, !track |
{key: env, operator: In, values: [prod, staging]} |
All requirements in a selector are ANDed. There is no OR between requirements (use in for OR within one key).
kubectl get pods -l tier=backend,environment=production
kubectl get pods -l 'environment in (production,staging),!canary'
kubectl get pods --show-labels
kubectl label pod api-7d9f-x2k4p track=canary --overwriteLet's implement the matching rules. This parser handles the kubectl selector syntax and evaluates it against a set of Pods:
import re
pods = {
"api-1": {"app": "api", "tier": "backend", "env": "prod", "track": "stable"},
"api-2": {"app": "api", "tier": "backend", "env": "prod", "track": "canary"},
"web-1": {"app": "web", "tier": "frontend", "env": "prod"},
"api-dev": {"app": "api", "tier": "backend", "env": "dev"},
"report": {"app": "report"},
}
def parse(selector):
reqs = []
for part in re.split(r",(?![^()]*\))", selector):
part = part.strip()
if m := re.fullmatch(r"(\S+)\s+(in|notin)\s+\((.*)\)", part):
reqs.append((m[1], m[2], {v.strip() for v in m[3].split(",")}))
elif m := re.fullmatch(r"(\S+?)(!=|==|=)(\S*)", part):
reqs.append((m[1], "!=" if m[2] == "!=" else "=", m[3]))
elif part.startswith("!"):
reqs.append((part[1:], "!exists", None))
else:
reqs.append((part, "exists", None))
return reqs
def matches(labels, reqs):
for key, op, value in reqs:
has, v = key in labels, labels.get(key)
if op == "=":
ok = v == value
elif op == "!=":
ok = v != value # also true when the key is missing
elif op == "in":
ok = has and v in value
elif op == "notin":
ok = not has or v not in value
elif op == "exists":
ok = has
else:
ok = not has
if not ok:
return False
return True
for sel in ["tier=backend", "app=api,env in (prod,staging)", "app=api,!track", "track", "env notin (dev),tier!=frontend"]:
picked = [name for name, labels in pods.items() if matches(labels, parse(sel))]
print(f"{sel:32} -> {picked}")tier=backend -> ['api-1', 'api-2', 'api-dev']
app=api,env in (prod,staging) -> ['api-1', 'api-2']
app=api,!track -> ['api-dev']
track -> ['api-1', 'api-2']
env notin (dev),tier!=frontend -> ['api-1', 'api-2', 'report']
Note the subtle rules in the last line: tier!=frontend and env notin (dev) also match Pods that don't have the key at all, which is why report (no tier, no env) is selected.
Selectors in manifests
Controllers use the YAML form, matchLabels plus optional matchExpressions:
selector:
matchLabels:
app: api
matchExpressions:
- {key: env, operator: In, values: [prod, staging]}
- {key: track, operator: NotIn, values: [canary]}
- {key: tier, operator: Exists}The model below parses that YAML with PyYAML and applies it:
import yaml
selector = yaml.safe_load("""
matchLabels:
app: api
matchExpressions:
- {key: env, operator: In, values: [prod, staging]}
- {key: track, operator: NotIn, values: [canary]}
- {key: tier, operator: Exists}
""")
def selects(sel, labels):
if any(labels.get(k) != v for k, v in sel.get("matchLabels", {}).items()):
return False
for e in sel.get("matchExpressions", []):
k, op, vals = e["key"], e["operator"], e.get("values", [])
if op == "In" and labels.get(k) not in vals:
return False
if op == "NotIn" and k in labels and labels[k] in vals:
return False
if op == "Exists" and k not in labels:
return False
if op == "DoesNotExist" and k in labels:
return False
return True
pods = {
"api-1": {"app": "api", "tier": "backend", "env": "prod", "track": "stable"},
"api-2": {"app": "api", "tier": "backend", "env": "prod", "track": "canary"},
"api-3": {"app": "api", "tier": "backend", "env": "staging"},
"api-4": {"app": "api", "env": "prod"},
}
for name, labels in pods.items():
print(name, selects(selector, labels))api-1 True
api-2 False
api-3 True
api-4 False
Warning: A Deployment's
spec.selectormust match the labels in its Pod template, and it is immutable after creation. If two controllers' selectors overlap, they fight over the same Pods. Use a distinctive label set per workload.
Annotations
Annotations are also key/value pairs in metadata, but they are not used for selection. They hold non-identifying information, often for tools: values can be large (up to 256 KiB in total) and contain any text.
metadata:
annotations:
kubernetes.io/change-cause: "upgrade to 2.3.1 (ticket OPS-412)"
prometheus.io/scrape: "true"
owner: "team-payments@example.com"
deployment.kubernetes.io/revision: "4" # set by the Deployment controller| Labels | Annotations | |
|---|---|---|
| Used by selectors | yes | no |
| Value size | ≤ 63 chars | large, free text |
| Typical content | app, tier, env, version | build info, owners, tool configuration |
Test yourself
Which selector matches Pods that have no track label at all?
- track
- !track
- track=
- track in ()
How are multiple requirements in one selector combined?
- OR
- AND
- XOR
- Only the first is used
Where should you store a build's Git commit and the owning team's e-mail?
- Labels
- Annotations
- The object name
- spec.selector