With time the .kube/config file will contain a mix of dev, test and prod cluster references.
It is easy to forget switching off from a prod cluster context and make a mistake and run for example kubectl delete ns crossplane-system
.
Use the following setup to avoid these kinds of errors and keep clusters separate.
Direnv is on most Linux distros and it's easy to set it up on a Mac
brew install direnv
echo eval "$(direnv hook bash)" >> ~/.bashrc
Especially for connecting to important prod clusters, use a dedicated directory.
Proposed naming convetion:
[kube]-name-of-the-cluster
mkdir kube-prod-cluster && cd kube-prod-cluster
This file contains KUBECONFIG variable that is scoped only to the current directory and all subirectories
echo export KUBECONFIG="$PWD"/config >> .envrc
direnv allow
Inside the directory, connect to any cluster, for example
gcloud container clusters get-credentials creds --region us-west1 --project project-name
By leaving the folder, direnv will unload the local KUBECONFIG variable and set the previous shell variable.
Dedicated folders allow for storing notes, troubleshooting steps etc and can be easily converted into git repositories if needed.
A few alternative approaches collected from the accompanying Reddit thread
# Note the space at the end of the commands
alias ktest="kubectl --kubeconfig ~/.kube/config-test "
alias kprod="kubectl --kubeconfig ~/.kube/config-prod "