I’ll introduce how to manage environment variables with direnv.
- Official site: direnv - unclutter your .profile
- GitHub: direnv/direnv: Unclutter your .profile
Prerequisites
Similar Libraries *dotenv
There are dotenv-style libraries as similar libraries to direnv.
- Node.js: motdotla/dotenv
- PHP: vlucas/phpdotenv
- Python: theskumar/python-dotenv
- Ruby: bkeepers/dotenv
Benefits of 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.
Installing direnv
macOS Edition
On macOS, installing with Homebrew is easy.
brew install direnv
Add Hook to Shell
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.
Using direnv with New .envrc
direnv edit .
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
direnv: loading
$ cd /path/to/envrc/dir
direnv: loading .envrc
direnv: export +AWS_ACCESS_KEY_ID +AWS_DEFAULT_REGION +AWS_SECRET_ACCESS_KEY
Using direnv with Existing .envrc
Run direnv allow if Error Occurs
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.
Other direnv Tips
direnv: unloading
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.