IN-Decent

Re-decentralizing internet with free software

Autoset Environment Variables and Virtual Environments With direnv

Posted at — Aug 27, 2023

direnv is a utility program for Unix which automatically sets and unset environment variables when user enters and leaves a directory respectively.

It checks for the presence of .envrc or optionally .env files in a directory and if it is present it loads them automatically when entering a directory and unloads them when leaving a directory.

Installation:

direnv can be installed either using Operating system’s package manager or by downloading the binary or by compiling from the sources. Refer the installation documentation for more details.

Setup

Once installed, it needs to be hooked into the user’s shell. Here is an example for bash shell:

Add the below line to end of ~/.bashrc file.

eval "$(direnv hook bash)"

For example on how to do it for other shells, refer official documentation here

Usage

Inside the project directory, create a .envrc file and add the project specific environment variables to this file.

cd project_dir
echo "export secret=token" > .envrc

It also has a security feature that only loads a previously allowed contents to be added and if the .envrc or .env file is changed it prompts for the user to allow the changes before the modified variables are loaded. Since we are creating for the first time we need to approve it once for the .envrc file contents to be loaded. This can be done by the below command,

# direnv: error project_dir/.envrc is blocked. Run `direnv allow` to approve its content
direnv allow

# once the file is allowed the variables will be automatically loaded and unloaded on entering and exiting
cd project_dir
# direnv: loading project_dir/.envrc
# direnv: export +secret

echo ${secret-nope}
# token

# on leaving the directory
cd ~
# direnv: unloading

echo ${secret-nope}
# nope

This tool can also be used to automatically create and activate virtual environments for python etc.

# to automatically create a python virtual environment and activate it.
# add the below line to .envrc file
layout python python3.11

This uses python venv tool to create the virtual environment inside the project directory in location .direnv/. Although the virtual environment is activated, the prompt will not be changed by default.

direnv has many other collection of utility functions that can be used in the .envrc file called the stdlib.

References:

  1. direnv official website
  2. direnv stdlib
  3. direnv community wiki