Skip to content
Latchkey

kubectl config use-context: Select the Target Cluster

kubectl config use-context sets which context (cluster + user + namespace) subsequent commands target.

A runner may have several clusters in its kubeconfig. Selecting the right context first prevents a deploy from landing in the wrong place.

What it does

kubectl config use-context changes the current-context in the active kubeconfig, which determines the cluster endpoint, the credentials, and the default namespace for every following command. Related verbs read or modify contexts: get-contexts lists them, current-context prints the active one, and set-context edits fields.

Common usage

Terminal
kubectl config get-contexts
kubectl config use-context staging
# set the default namespace on the current context
kubectl config set-context --current --namespace=staging
# confirm what is active before deploying
kubectl config current-context

Options

Command / FlagWhat it does
use-context <name>Set the active context
get-contextsList all contexts (asterisk marks the current)
current-contextPrint the active context name
set-context --current --namespace=<ns>Change the namespace of the active context
--kubeconfig=<file>Operate on a specific kubeconfig file

In CI

On a shared runner, prefer setting KUBECONFIG to a job-scoped file or passing --context per command, since use-context mutates shared kubeconfig state that another concurrent job may read. Print kubectl config current-context early so the job log records exactly which cluster it touched.

Common errors in CI

"error: no context exists with the name: \"staging\"" means the context is not in this kubeconfig; check kubectl config get-contexts and the spelling. "error: open <path>: no such file or directory" means KUBECONFIG points at a missing file. After use-context, a "The connection to the server localhost:8080 was refused" means the context has no cluster server set (an empty or default kubeconfig).

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →