Aug 16, 2017

How to set Heroku environmental variables from dotenv (.env) files

TL;DR

sed 's/#[^("|'')]*$//;s/^#.*$//' .env | \
  xargs heroku config:set --app=YOUR-APP

Heroku allows you to set and unset environmental variables using their CLI, but manually writing the values is tedious, and sometimes you need to bulk set values, for instance to sync values from your local environment to your staging environment.

A very simple way of doing this is importing the values from a dotenv (.env) file with the following command:

sed 's/#[^("|'')]*$//;s/^#.*$//' .env | \
  xargs heroku config:set --app=YOUR-APP

Explanation

We have 3 commands here:

  • # sed
  • # xargs
  • # heroku

sed

The sed command reads a file line by line, applies the transformations you supply, and outputs the modified text.

In this case, we are removing comments from our file with sed 's/#[^("|'')]*$//;s/^#.*$//' which in plain English means: remove any hash, and everything after it, only if no quote marks are found after the hash, unless it is the first character in the line, in which case remove the whole line even if there are quotes. Sounds confusing? This explains it better:

Some examples:

VAR=value # Comment will get removed.
VAR=value # Comment won't get removed, because it has a quote mark.
VAR="value with a #" # The value will keep the hash, comment gets removed.
# Line gets removed.
# Line gets removed, even with this: ".
  • Comments beginning with a hash (#)
  • If a hash is within quote marks, it is not a comment and won't be removed.
  • If a quote mark, single or double, is found after the hash, it won't be detected as a comment (because it is pretty much impossible to do so with regular expressions).
  • If the line begins with a hash, remove it regardless of quote marks.

xargs

The next command we execute reads from standard input (in our case, the output from the sed command), and converts the text it reads into valid parameters and executes a command passing those parameters to it.

The reason we need it is so that quotes from the dotenv file are not taken literally. Without xargs, a definition like VAR="quoted value", would end up setting the quotes as part of the value like: "quoted value", which we do not want. We want the value to be quoted value.

heroku

Finally, the heroku command will be executed with a list of variables to be set, which it receives from xargs, and sets all the variables in your app.

Comments