<p>My bash scripts with <code>kubectl</code> sometimes cause trouble when it changes context. After running the script user may accidentally end up make changes in wrong cluster. I would like to probe your wisdom when it comes to handling context in scripts.</p>
<p>Is it possible for the script to save old context and when done revert the old context back? (I thought about running <code>kubectl config get-contexts</code> find current context and set it back after script completes. But this may fail if user haven't saved contexts)</p>
<p>Other approach I am thinking is to save the value of KUBECONFIG env var, change it to a temp file, get credentials and restore the value when the script completes.</p>
<p>Before I go and reinvent the wheel I like to here how the power users are handling situation like this? Can you share your thoughts/ideas?</p>

RandomQuests
<p>Generally, I think it's problematic to depend implicitly on global state that may be arbitrarily updated by other processes and users.</p>
<p>Even with multiple configuration files, there's still opacity as to which cluster, user, namespace, context are being used.</p>
<p>For a single user, <code>kubectl</code>'s configuration file provides the convenience of not having to retype flags for every command and I think that should be it's sole purpose.</p>
<p>In scripts, I think it's preferable (clearer|self-documenting) to be explicit and to include either <code>--context</code> or <code>--cluster</code>, <code>--user</code> (and possibly <code>--namespace</code>) every time.</p>
<p>This said, it is also advisable to use variables rather than hard-coded values so there's still room for error.</p>
<pre class="lang-sh prettyprint-override"><code>kubectl delete deployment/primary-service

# vs

KUBECONFIG=sam-monday-morning-config.yaml \
kubectl delete deplopyment/primary-service

# vs

kubectl delete deployment/primary-service \
--cluster=test-cluster \
--namespace=test-namespace \
--user=test-user
</code></pre>
