kubectl config set-context: Command Reference for CI/CD
Create or modify a context, or pin a default namespace.
kubectl config set-context edits a context entry: which cluster, which user, and which default namespace. Pinning the namespace once means every later command does not need -n. This reference covers the flags and a CI example.
Common flags and usage
- set-context --current --namespace=<ns>: pin a default namespace
- set-context <name> --cluster=<c> --user=<u> --namespace=<ns>: define a context
- --current: edit the active context in place
- Pair with use-context to define then switch
- set-credentials / set-cluster define the referenced parts
Example
kubectl config set-context --current --namespace=ci-${BUILD_ID}
kubectl get pods # no -n needed now
kubectl apply -f k8s/In CI
Pinning the namespace with --current --namespace at the top of a job removes a whole class of "wrong namespace" bugs from the rest of the script. It only edits the kubeconfig entry; the namespace must still exist for commands to succeed.
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
- --current --namespace pins a default so later commands skip -n.
- set-context edits the kubeconfig entry; it does not create the namespace.
- Define a context then use-context to switch to it.