---
title: "Toolbox 1: direnv"
date: 2021-05-17T21:24:00+01:00
aliases:
  - /posts/toolbox-1-direnv/
authors:
  - robert-kaussow
tags:
  - Sysadmin
  - Automation
resources:
  - name: feature
    src: "images/feature.jpg"
    params:
      anchor: Center
      credits: >
        [Fleur](https://unsplash.com/@yer_a_wizard) on
        [Unsplash](https://unsplash.com/photos/dQf7RZhMOJU)
---

We all use many different tools every day e.g. for our work, automation or better productivity. In the series "Toolbox" I would like to present such applications that have made my day-to-day work so much easier. All applications are free and open source software developed by big tech companies as well as lovingly handcrafted hobby projects. If you also know an awesome tool that has changed your life, I would love to hear from you on [Mastodon](https://social.tchncs.de/@xoxys).

## direnv

The basic function of [direnv](https://direnv.net/) is pretty simple, it manages environment variables depending on the current directory you are in. This may sound not very helpful, but it could save a lot of work, especially if you have to deal with many different project environments. I use it a lot combined with Ansible. Depending on the deployment environment I need to set a different remote user, also the roles should be loaded from a different base directory depending on whether it is a test or production environment.

As long as the required configuration can be set by an environment variable, direnv can handle it. All you have to do is to create a `.envrc` file in the directory where it should be loaded. A simple configuration could look like this:

```Shell
$ cat .envrc
export ANSIBLE_ROLES_PATH=/home/xoxys/devel/.roles/staging
export ANSIBLE_REMOTE_USER=project-1
```

Each time you create or modify an `.envrc` file, you must approve the modification by running `direnv allow`. This prevents direnv from loading a file that has been modified or created by another malicious process, for example. After you have approved the file, direnv will automatically load it when you navigate to the directory where your configuration is located. To make it even better, it doesn't have to be the root directory, the file will also be loaded if you navigate directly to a sub-directory. When you leave the directory, your environment will also be unloaded automatically.

Direnv is written in Golang and available in most Linux Distribution [repositories](https://direnv.net/docs/installation.html#from-system-packages). Binary builds can be downloaded from the [GitHub Release](https://github.com/direnv/direnv/releases) page as well.
