direnv
direnv is a shell extension that automatically loads and unloads environment variables when you enter and leave a directory. By combining it with varlock, you can get validated, schema-driven environment variables loaded directly into your shell session.
How it works
Section titled “How it works”direnv works by executing a .envrc file in your project directory and capturing any exported variables into the current shell. Varlock’s --format shell flag outputs your resolved env vars as export KEY=VALUE lines that direnv can capture via eval.
eval "$(varlock load --format shell)"When you cd into your project, direnv runs this command and exports all your validated environment variables into the shell.
-
Install direnv
Follow the official direnv installation guide for your platform and shell, then hook it into your shell profile. For example, for bash:
Terminal window echo 'eval "$(direnv hook bash)"' >> ~/.bashrc -
Create a
.envrcfile in your project root.envrc watch_file .env .env.*eval "$(varlock load --format shell)"The
watch_fileline tells direnv to re-evaluate whenever any of your.envfiles change. Note that new files added after the initial load will not be watched until you rundirenv reload— but this is rarely a concern since adding new env files is uncommon. -
Allow the
.envrcfileTerminal window direnv allow
How it looks
Section titled “How it looks”Once set up, when you cd into your project directory, direnv automatically loads your varlock-validated environment:
$ cd my-projectdirenv: loading .envrcdirenv: export +API_URL +DB_PASS +PORTAnd when you leave the directory, those variables are automatically unloaded.
Skip undefined values
Section titled “Skip undefined values”By default, varlock outputs an empty assignment for undefined optional variables (e.g. OPTIONAL_VAR=""). If you prefer to skip undefined values entirely, use the --compact flag:
watch_file .env .env.*eval "$(varlock load --format shell --compact)"