kubectl label: Usage, Options & Common CI Errors
Add, change, or strip labels - singly or in bulk.
kubectl label mutates the labels on one or more objects. Labels drive selectors, so labelling correctly is what makes Services, Deployments, and your own kubectl get -l queries find the right pods.
What it does
kubectl label RESOURCE NAME key=value adds a label; key- (trailing dash) removes it. By default labelling an existing key fails - pass --overwrite to change it. You can target many objects at once with -l (select by existing label) or --all within a namespace.
Common usage
kubectl label pod my-pod env=staging
kubectl label pod my-pod env=prod --overwrite
kubectl label pod my-pod env- # remove the label
kubectl label pods -l app=web tier=frontend # bulk by selectorCommon errors in CI
"\"env\" already has a value (staging), and --overwrite is false" is the re-run trap: the first run set the label, the retry fails because you did not pass --overwrite. Add --overwrite for idempotent scripts. "metadata.labels: Invalid value" means the value breaks the rules - label values must be ≤63 characters, alphanumeric plus -, _, ., starting and ending alphanumeric. Git branch names and image tags often violate this (slashes, leading digits via prefixes), 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 nodes