How to use different versions of globally installed applications like terraform, python, node, etc on a per project basis. This solution will work on any Mac or Linux distribution.
If you are like me and have many projects requiring different versions of global applications like terraform, python, node, etc., this solution is for you. Well, this solution is for you if you are on Mac or Linux.
Dynamically update PATH environment variable for each project based on the current directory or parent directory. I use direnv which is a great tool that extends your shell to load and unload environment variables depending on the current directory. And it probably supports your shell of choice as long as it is bash, zsh, fish, tcsh, or Elvish.
This how-to will use Mac OS, homebrew, and terraform; however, this solution will work for any platform or toolset.
Installing homebrew is easy:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
You can easily install direnv with homebrew:
brew install direnv
To install direnv on other systems, see the direnv Installation Documentation.
You can find the files created in this tutorial in my tips-tricks-workaround git repo.
brew install terraform # installs current version, 13
brew install terraform@0.12
Let’s take a look at what was installed and where:
# ls -od /usr/local/opt/terraform* /usr/local/bin/terraform* | awk '{print $8,$9,$10}'
/usr/local/bin/terraform -> ../Cellar/terraform/0.13.0_1/bin/terraform
/usr/local/opt/terraform -> ../Cellar/terraform/0.13.0_1
/usr/local/opt/terraform@0.12 -> ../Cellar/terraform@0.12/0.12.29
/usr/local/opt/terraform@0.13 -> ../Cellar/terraform/0.13.0_1
brew unlink terraform
~/Projects
):/Projects/project-acme/
/Projects/project-beta/
/Projects/project-charlie/
Projects
directory, create a .envrc
:export TF12_PATH=/usr/local/opt/terraform@0.12/bin
export TF13_PATH=/usr/local/opt/terraform/bin # Terraform 13
.envrc
in each project:source_up
PATH_add $TF13_PATH
This setup ensures that when you cd
into each project directory, the PATH points to the correct terraform version:
~/Projects
# type terraform
type: Could not find 'terraform'
~/Projects/project-acme
# type terraform
terraform is /usr/local/opt/terraform@0.13/bin/terraform
~/Projects/project-beta
# type terraform
terraform is /usr/local/opt/terraform@0.12/bin/terraform
If you want a fallback version:
export TF12_PATH=/usr/local/opt/terraform@0.12/bin
export TF13_PATH=/usr/local/opt/terraform@0.13/bin
# Optional: If you want a default terraform, add it here.
PATH_add $TF12_PATH
You can also add these exports to your shell profile files:
~/.bashrc
~/.zshrc
~/.config/fish/config.fish