DotenvParser - A simple library to parse .env files

I was refactoring my project to use config/runtime.exs to make the config more streamlined and allow configuring (nearly) all things with environment variables. This is fine for production where I define the variables in the Systemd unit file, but in development I don’t want to waste time having to set all of them or remembering to source them from somewhere.

So I decided to write a simple .env file parsing library so I can do this on top of my config file:

if Config.config_env() == :dev do
  DotenvParser.load_file(".env")
end

Now for developers, all the vars are nicely grabbed from the .env and they can be used in the runtime config (or inside the application code) with System.get_env/2. When execution ends, they are no longer set, so they don’t pollute your shell environment.

The library supports both uppercase and lowercase variable names, quoted values to prevent trimming of whitespace, comment lines and inline comments, double quoted values to unescape some escape codes like \n or \uXXXX, and lines that start with export (in case you want shell compatibility – but note that the escapes may be different).

Link to library: https://hex.pm/packages/dotenv_parser

License: MIT (+ BSD 3 clause for one test file)

5 Likes

Some prior art, some of them I looked through and some I didn’t know of before this moment:

dotenv – I figured it was abandoned but in fact at pretty much the same time as I made my own, it has reactivated and pushed a new version. :smiley: Has a server mode with a reload function to reload values when they have been changed. Supports referring to previous variables in subsequent ones, which mine doesn’t. Doesn’t seem to have any unescape support?

envy – Puts values directly to system env (no possibility to return them). Doesn’t do unescaping. Has a Mix-based config reload system.

stillir – In Erlang, I don’t know how to use it.

exenv – Has different adapters and encryption support.

4 Likes

Serving suggestion

Since environment variables are always strings, so I wrote this helper function to grab variables and cast them to the correct type: https://gitlab.com/code-stats/code-stats/-/blob/d189c46930d1c352af8ca63027d56b346814ab32/lib/code_stats_web/config_helpers.ex

You can see it in action in the aforementioned config/runtime.exs file.