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
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.
Using this in CI
A runner has no kubeconfig, no cached context, and no interactive auth. Every kubectl invocation in CI needs the context supplied explicitly, and most confusing CI failures here are the command running against the wrong cluster or no cluster at all.
# never rely on the ambient context on a runner
kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pods
# confirm what you are actually connected to before mutating anything
kubectl config current-context
kubectl cluster-info
# fail fast instead of hanging on an unreachable API server
kubectl --request-timeout=30s get nodesKey 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.