Skip to content

Instantly share code, notes, and snippets.

@Piotr1215
Last active April 18, 2022 12:22
Show Gist options
  • Save Piotr1215/6486cefaf2d72d3ff840e38f3265c655 to your computer and use it in GitHub Desktop.
Save Piotr1215/6486cefaf2d72d3ff840e38f3265c655 to your computer and use it in GitHub Desktop.
Keep cluster connections separate

How to keep cluster connections cleanly separated

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.

Direnv based setup

Use the following setup to avoid these kinds of errors and keep clusters separate.

Install direnv

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

Create directory per cluster

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

Create .envrc file

This file contains KUBECONFIG variable that is scoped only to the current directory and all subirectories

echo export KUBECONFIG="$PWD"/config >> .envrc

Enable direnv in the directory

direnv allow

Connect to cluser

Inside the directory, connect to any cluster, for example

gcloud container clusters get-credentials creds --region us-west1 --project project-name

Leave the folder

By leaving the folder, direnv will unload the local KUBECONFIG variable and set the previous shell variable.

Bonus workflow

Dedicated folders allow for storing notes, troubleshooting steps etc and can be easily converted into git repositories if needed.

Alternative approaches

A few alternative approaches collected from the accompanying Reddit thread

Aliases per cluster

# Note the space at the end of the commands
alias ktest="kubectl --kubeconfig ~/.kube/config-test "
alias kprod="kubectl --kubeconfig ~/.kube/config-prod "

https://www.reddit.com/r/kubernetes/comments/u5n46i/comment/i53m0h4/?utm_source=share&utm_medium=web2x&context=3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment