<p>Consider a simple script:</p>

<pre><code>kubectl create -f foo.yaml
kubectl expose deployment foo
</code></pre>

<p>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 <code>kubectl config set-context</code> while the script is running.) How do you resolve that?  How can I ensure consistency? </p>

William Pursell
<p>I suggest to always use <code>--context</code> flag:</p>

<pre><code>$ kubectl options | grep context
      --context='': The name of the kubeconfig context to use
</code></pre>

<p>for each <code>kubectl</code> command in order to define a context and prevent an issue described in a question:</p>

<pre><code>ENV=&lt;env_name&gt;
kubectl create --context=$ENV -f foo.yaml
kubectl expose --context=$ENV deployment foo
</code></pre>
