kubens: Switch the Active Namespace
kubens <namespace> sets the default namespace on the current context, so later kubectl commands skip the -n flag.
kubens is the namespace sibling of kubectx. Set the namespace once and every kubectl in the job targets it without -n.
What it does
kubens writes the namespace field of the current context in kubeconfig. With no argument it lists all namespaces and highlights the active one; - switches back to the previous namespace.
Common usage
kubens # list namespaces, active one highlighted
kubens payments # make "payments" the default
kubens - # back to the previous namespace
kubectl get pods # now scoped to payments, no -n neededOptions
| Form | What it does |
|---|---|
| kubens | List namespaces |
| kubens <name> | Set the default namespace |
| kubens - | Switch to the previous namespace |
| kubens -c, --current | Print the current namespace only |
In CI
Run kubens <ns> early in a job so subsequent kubectl, helm, and stern calls inherit it. Note it edits kubeconfig, so on a shared runner give each job its own KUBECONFIG copy to avoid cross-job namespace bleed.
Common errors in CI
error: no namespace exists with the name: "payments" means the namespace is not yet created in that cluster; create it or check the spelling. If kubeconfig is read-only (a common mounted-secret setup), kubens fails to persist with permission denied; pass -n per command instead.
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