kubectl label: Command Reference for CI/CD
Add, change, or strip labels, singly or in bulk.
kubectl label mutates the labels that drive selectors. Getting labels right is what makes Services and your own get -l queries find the right pods. This reference covers the syntax, idempotency, and the value-format rules CI inputs often violate.
Common flags and usage
- label <res> <name> k=v: add a label
- label <res> <name> k-: remove a label (trailing dash)
- --overwrite: change an existing label (required for re-runs)
- -l <selector>: label every object matching a selector
- --all: label all objects of a type in the namespace
Example
shell
SAFE_TAG=$(echo "${GIT_BRANCH}" | tr '/' '-' | cut -c1-63)
kubectl label deploy/web branch="${SAFE_TAG}" --overwrite
kubectl label pods -l app=web tier=frontend --overwriteIn CI
Re-running without --overwrite fails with "already has a value". Add --overwrite for idempotent scripts. Label values must be <=63 chars, alphanumeric plus -, _, ., starting and ending alphanumeric; git branch names with slashes break this, so sanitize before labelling.
Key takeaways
- Add --overwrite so re-runs do not fail on an existing label.
- Label values are <=63 chars with strict character rules; sanitize CI inputs.
- A trailing dash (k-) removes a label.
Related guides
kubectl Cheat Sheet: Commands for Everyday KubernetesA kubectl cheat sheet - get, describe, logs, apply, rollout, debug, and context commands for daily Kubernetes…
kubectl annotate: Command Reference for CI/CDReference for kubectl annotate: attach non-identifying metadata to resources, the change-cause annotation for…
kubectl get: Command Reference for CI/CDReference for kubectl get: list resources, output formats, label and field selectors, jsonpath extraction, an…
kubectl patch: Command Reference for CI/CDReference for kubectl patch: apply strategic-merge, JSON-merge, or JSON-patch updates from a script, when to…