Ensure kubectl is running in the correct context

5/15/2018

Consider a simple script:

kubectl create -f foo.yaml
kubectl expose deployment foo

There seems to be a race condition, and no way to guarantee that the context of the second command runs in the same context as the first. (Consider the user going to another shell and invoking kubectl config set-context while the script is running.) How do you resolve that? How can I ensure consistency?

-- William Pursell
kubernetes

1 Answer

5/15/2018

I suggest to always use --context flag:

$ kubectl options | grep context
      --context='': The name of the kubeconfig context to use

for each kubectl command in order to define a context and prevent an issue described in a question:

ENV=<env_name>
kubectl create --context=$ENV -f foo.yaml
kubectl expose --context=$ENV deployment foo
-- nickgryg
Source: StackOverflow