Kubernetes: specify cluster context in apply command
There seems to be --context=...
option.
kubectl optionsThe following options can be passed to any command:... --context='': The name of the kubeconfig context to use
at least in version v1.18.6
kubectl
takes a --context
option:
kubectl --context cluster-1-context apply -f ./deploy-to-cluster-1.yml
There's no way to specify or enforce this in resource YAML files; it's still possible to have accidents.
If you have multiple .kube/config
files, you can also set the $KUBECONFIG
environment variable to point at one of those. This is understood by the standard Kubernetes SDKs, so almost all tools should support it.
export KUBECONFIG=./cluster-1-config.ymlkubectly apply -f ./deploy-to-cluster-1.yml
(Given the choice I would prefer this approach, because environment variables are shell-local but kubectl config current-context
will affect all of my open terminal windows. Standard tooling that configures the .kube/config
file tends to default to the single shared global file, though, and teasing it apart can be a little tricky.)
Is there a better way to do this?
You can use kubectx tool to switch between contexts back and forth in a much easier way than kubectl.
USAGE: kubectx : list the contexts kubectx <NAME> : switch to context <NAME> kubectx - : switch to the previous context kubectx -c, --current : show the current context name kubectx <NEW_NAME>=<NAME> : rename context <NAME> to <NEW_NAME> kubectx <NEW_NAME>=. : rename current-context to <NEW_NAME> kubectx -d <NAME> : delete context <NAME> ('.' for current-context) (this command won't delete the user/cluster entry that is used by the context) kubectx -u, --unset : unset the current context$ kubectx minikubeSwitched to context "minikube".$ kubectx -Switched to context "oregon".$ kubectx -Switched to context "minikube".$ kubectx dublin=gke_ahmetb_europe-west1-b_dublinContext "dublin" set.Aliased "gke_ahmetb_europe-west1-b_dublin" as "dublin".
As it stands out today there is no way to specify context as part of deployment yaml. You can submit a feature request in kubernetes GitHub repo for this.