Set & load environment variables in a phoenix app

Viewed 7699

I'm new to a Phoenix framework and am looking for a way to set environment variables in the app. One way I found is here.

However, I don't like this way since I need to type source .env whenever I restart the app.

I tried setting the ENV variables in prod.secret.exs like below:

config :oauth,
  GITHUB_CLIENT_ID: "(CLIENT ID)",
  GITHUB_CLIENT_SECRET: "(SECRET)"

And I tried retrieving ENV variables in a following way:

 config :ueberauth, Ueberauth.Strategy.Github.OAuth,
   client_id: System.get_env("GITHUB_CLIENT_ID"),
   client_secret: System.get_env("GITHUB_CLIENT_SECRET")

However, when I run the server using mix phoenix.server, it gives me an error like below and I'm not sure what it really means:

You have configured application :oauth in your configuration
file, but the application is not available.

This usually means one of:

1. You have not added the application as a dependency in a mix.exs file.

2. You are configuring an application that does not really exist.

Please ensure :oauth exists or remove the configuration.

I'm looking for a way to save ENV variables in the project itself in a hidden file so it can be retrieved anytime I want. Can someone tell me what's the right way of saving ENV variables and retrieving them in a Phoenix app?

3 Answers

I have found another example

1.- Create a file .env in you main folder

2.- Add the env variables in the .env file

# Example:
# MyApp/.env file
export GITHUB_CLIENT_ID="testID"
export GITHUB_SECRET_CLIENT_ID="testSecretID"

3.- Run source .env and every time it is modified, execute the command again, maybe in reboot too

4.- What is really important - don't forget to add your secret files to MyApp/.gitignore

# add this at the end
/.env

5.- Run phoenix server mix phx.server or mix phoenix.server

You can test it with

iex -S mix phoenix.server

iex> System.get_env("GITHUB_CLIENT_ID")
"testID"

Links of help:

Environment variable error
Documentation of config

Related