August 31, 2021
Changing environments per directory
tmux as a tool with a colleague the question came up: could we automagically switch the
gcloud configuration when switching between
For example, I have a
tmux session for a project called TrainTrack.
When I’m working on that project I’d like to have my
gcloud config point to a specific GCP project.
And when I switch
tmux sessions to work on my
dispatcher project, I similarly want to have the
gcloud configuration switch—automatically—to the relevant GCP project.
You can achieve this manually by setting an environment variable called
CLOUDSDK_ACTIVE_CONFIG_NAME, so what I need is a way to change that ENV variable automatically when I switch working directories.
The Google documentation points to
direnv as a viable solution.
It uses the presence of a
.envrc file in a directory to trigger loading and unloading and resetting ENV values.
Piece of cake on Mac:
brew install direnv then integrate into your shell.
tmux so I created a session where I have two project directories open, one per pane.
My goal is to be able to simple switch between panes in the same
tmux session and have the
gcloud configuration change automatically.
Pane #1 - I’m in a directory called
At this point
direnv let me know that it needs permission to automatically update environment variables:
Pane #2 - directory for my ‘dispatcher’ project that needs a different
gcloud config. Note the different value for the
CLOUDSDK_ACTIVE_CONFIG_NAME variable that the
gcloud command is watching for:
Proving it out
tmux open and two panes side-by-side I start in pane #1:
Bingo! I have the correct configuration
[dispatcher] for this project directory.
Then switch to Pane #2 and run the same command:
And yes! Without doing anything at all I have the correct and expected
gcloud configuration with the right project, etc.
I can see this being really useful for configuring 12 Factor apps.