Direnv: Multiple dotenv

Created on 25 Nov 2019  路  3Comments  路  Source: direnv/direnv

It's often a case that locally developer has different environment variables depending if just running the app or running tests (like e.g. database url).

Ruby dotenv allows you to have multiple different .env files with environment name suffix like .env.local, .env.development or .env.test.local.

It would be really helpful if I could somehow dynamically switch between dotenv files depending on some defined context or at least easy way to make a switch with a command. Or maybe it's already possible somehow?

Feature

Most helpful comment

@glensc You may add .envrc file to the VCS and add following to the end of it:

[[ -f .envrc.local ]] && dotenv ".envrc.local"

All 3 comments

You could write a little direnv-switch wrapper function like this:

#!/usr/bin/env bash
# Usage: direnv-switch <env-name>
set -euo pipefail

# take the env as the first argument
env_name=$1
env_file=.env.${env_name}

# check if the .env.$env_name exists
if [[ ! -f $env_file ]]; then
  echo "env $env_name not found" >&2
  exit 1
fi

# create a new .envrc for the user
cat <<NEW_ENVRC > .envrc
log Loading environment "$env_name"
dotenv "$env_file"
NEW_ENVRC
# allow the execution
direnv allow .

The script assumes that the user is at the repo root, you can maybe first cd "$(git rev-parse --show-toplevel)" if you are using git for development.

The user then run:

$ direnv-switch test
direnv: loading .envrc
Loading environment "test"
direnv: export ...
$ 

You might also want to add a default environment, handling for .local files, ...

The main downside is that all shells will switch to that environment on next prompt.

Perhaps different request, but I would like to load .envrc, .envrc.dist, .envrc.local, i.e load when present, without extra dynamic logic for variable filename.

The purpose is to keep .envrc.dist in VCS for sharing with other devlopers, while adding .envrc.local to .gitignore

@glensc You may add .envrc file to the VCS and add following to the end of it:

[[ -f .envrc.local ]] && dotenv ".envrc.local"
Was this page helpful?
0 / 5 - 0 ratings