# Direnv

Learn how to automatically load environment variables in your development environment.

`direnv` is a tool that automatically loads environment variables when you `cd` into a directory and removes them when you leave that directory. This guide shows how to use it together with Tuna.

> **Attention.** We do not recommend loading all secrets into the shell environment this way. However, some developers may need this functionality. This is purely a guide on using Tuna Secrets with `direnv` and is not a recommendation of this tool or workflow.

## Requirements

* Install [direnv](https://direnv.net/)
* A shell compatible with `direnv`

## Project Setup

To do this, you first need to run the `tuna secrets setup` command in the project. Make sure you have completed the setup process and linked the directory to a project and configuration.

## Creating the `.envrc` File

In the root of the project directory, create a `.envrc` file with the following content:

> **Tip.** **Option 1** appeared later, as the `env-no-quotes` flag was added in a later version of the client.

**Option 1**

```shell
export <(tuna secrets download --no-file --format env-no-quotes)

```

**Option 2**

```shell
set -a
source <(tuna secrets download --no-file --format env)
set +a

```

The `set -a` command enables automatic export of all subsequent variable assignments, and `set +a` disables this feature.

***

After saving, you may receive a warning from `direnv`:

```shell
direnv: error /path/to/project/.envrc is blocked. Run `direnv allow` to approve its content

```

By default, `direnv` will not load the contents of the `.envrc` file until you approve it. Since you just created it, allow execution with:

```shell
direnv allow

```

After that, you will see a message about loading environment variables:

```shell
direnv: loading /path/to/project/.envrc
direnv: export +YOUR_VARIABLE

```

When you leave the directory, `direnv` will unload the variables:

```shell
direnv: unloading

```

> **The above solution does not guarantee correct operation with all secret values. In particular, errors may occur with multiline secrets. Direnv may also incorrectly handle secrets containing characters `?`, `*` and \`\`\`. There may also be issues with other characters (e.g., `$` and `#`).**

## Overriding Individual Variables

In some cases, you may need local overrides that are inconvenient to set through [configurations](https://tuna.am/en/docs/secrets.md#configurations). In this case, you can modify the `.envrc` file to look for another file and, if it exists, include it after loading secrets from Tuna. Let's call this file `.env.local`, and your `.envrc` will look like this:

```shell
set -a
source <(tuna secrets download --no-file --format env)
test -f .env.local && source .env.local
set +a

```

It will work the same as before, but if the `.env.local` file exists, the environment variables defined in it will take priority over those loaded from Tuna.
