I’ll introduce how to manage environment variables with direnv.
There are dotenv-style libraries as similar libraries to direnv.
*dotenv requires explicitly calling Dotenv.load from source code to load environment variables.
direnv’s benefit is that you don’t need to explicitly write Dotenv.load in source code, and it automatically activates when you move to a directory.
Another benefit is that you don’t need to use different *dotenv libraries depending on programming languages like Node.js or Ruby. By the way, direnv is written in Go.
On macOS, installing with Homebrew is easy.
brew install direnv
Refer to Setup to add a hook to your shell.
For zsh
Since I use zsh, I’ll introduce the zsh case.
Just add the following code to your ~/.zshrc file.
eval "$(direnv hook zsh)"
Don’t forget to run source ~/.zshrc or reopen Terminal after adding the above.
direnv edit .
Write the environment variables you want to load in the .envrc file using export as follows.
# .envrc
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID
export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY
$ cd /path/to/envrc/dir
direnv: loading .envrc
direnv: export +AWS_ACCESS_KEY_ID +AWS_DEFAULT_REGION +AWS_SECRET_ACCESS_KEY
If you see the error message direnv: error .envrc is blocked. Run direnv allow
to approve its content., run direnv allow as indicated in the error message.
When you move away from a directory with direnv configured, environment variables are automatically unloaded.
$ cd ../
direnv: unloading
That’s all from the Gemba on wanting to manage environment variables with direnv.