Handle environment variables the Elixir way

Created: May 13, 2019 21:25 | Updated: May 14, 2019 07:14
Tags: Elixir, Phoenix

Credit to this StackOverflow article

(all commands are performed from the root of the mix project)

If you take a look in your config folder you will find a number of configuration files.

config.exs is the main config file that applies to all environments. At the end of that file is the line import_config "#{Mix.env()}.exs" This loads one of the 3 files: prod.exs, dev.exs, or test.exsdepending on what your current environment is.

Like Inception, lets go one level deeper. And the end of prod.exs is the line import_config "prod.secret.exs" which imports your environment variables.

For some reason there is no dev.secret.exs, let's fix that!

touch config/dev.secrets.exs

Add it to your .gitignore before it's too late! I'm adding prod as well.

touch .gitignore
echo "config/dev.secret.exs" >> .gitignore
echo "config/prod.secret.exs" >> .gitignore

Import it at the end of dev.exs and test.exs

# dev.exs and test.exs

# everything else
import_config "dev.secret.exs"

Add your config variables

# dev.secret.exs

use Mix.Config

config :my_app, api_key: "1234567890"

Call it in your code

def do_stuff do
  api_key = Application.get_env(:my_app, :api_key)
end

Back up your secret files to somewhere safe and secure.

And make sure that git isn't about to upload your secrets to the whole internet

git status

Yay!

Written by Alan Vardy. Let me know how I can make this better!