Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes: specify cluster context in apply command

I have multiple kubernetes clusters and want to ensure that when I kubectl apply a deployment, I'm targeting the correct cluster.

I have all my clusters configured in contexts in the root /.kube/config file but I don't want to rely on statefully switching my current context to the correct one before running each apply command.

i.e. This is not satisfactory

kubectl config use-context cluster-1-context
kubectl apply ./deploy-to-cluster-1.yml

kubectl config use-context cluster-2-context
kubectl apply ./deploy-to-cluster-2.yml

I read the docs on config for multiple clusters and the only way I can find to do this is by copy/pasting the config for a particular cluster into a custom config file and specifying that with the --kubeconfig option on the apply command.

kubectl apply ./deploy-to-cluster-1.yml --kubeconfig ./config-cluster-1
kubectl apply ./deploy-to-cluster-2.yml --kubeconfig ./config-cluster-2

This works, but it seems really cumbersome.

For such a common requirement I'd expect there to just be a simple option on apply, or perhaps even a field in the deployment yml, that lets you specify (or restrict) the deployment to a particular context/cluster name, but I've read through a lot of the relevant documentation and can't find any such option.

Is there a better way to do this?

like image 895
davnicwil Avatar asked Dec 12 '25 02:12

davnicwil


2 Answers

There seems to be --context=... option.

kubectl options

The following options can be passed to any command:
...
      --context='': The name of the kubeconfig context to use

at least in version v1.18.6

like image 180
rkosegi Avatar answered Dec 13 '25 19:12

rkosegi


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.yml
kubectly 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.)

like image 20
David Maze Avatar answered Dec 13 '25 20:12

David Maze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!