How to get a variable value from Environment files in Phoenix?

12.3k views Asked by At

I'm deploying my first Phoenix Application, and I've specified the values of a variable in my Environment Files (dev.exs and prod.exs).

Now I'm trying to figure out how to access them in my Controllers.

# config/dev.exs
config :my_app, MyApp.Endpoint,
  http: [port: 4000],
  debug_errors: true,
  cache_static_lookup: false,
  my_var: "DEVELOPMENT VALUE"

# config/prod.exs
config :my_app, MyApp.Endpoint,
  http: [port: {:system, "PORT"}],
  url: [host: "example.com"],
  my_var: "PRODUCTION VALUE"
2

There are 2 answers

6
Sheharyar On BEST ANSWER

Okay, found something. Elixir's Application.get_env/3 is the way to go:

get_env(app, key, default \\ nil)


But the problem with this is that the accessor command becomes very long for the current situation:

# Set value in config/some_env_file.exs
config :my_large_app_name, MyLargeAppName.Endpoint,
  http: [port: {:system, "PORT"}],
  url: [host: "example.com"],
  my_var: "MY ENV VARIABLE"

# Get it back
Application.get_env(:my_large_app_name, MyLargeAppName.Endpoint)[:my_var]

A better way would be to define them in a separate section:

config :app_vars,
  a_string: "Some String",
  some_list: [a: 1, b: 2, c: 3], 
  another_bool: true

and access them like this:

Application.get_env(:app_vars, :a_string)
# => "Some String"

Or you could fetch a list of all key-value pairs:

Application.get_all_env(:app_vars)           
# => [a_string: "Some String", some_list: [a: 1, b: 2, c: 3], another_bool: true]
0
douarbou On

I had some bug with @sheharyar solution, so here mean:

I had to create new block without MyLargeAppName.Endpoint,

# Set value in config/some_env_file.exs
config :my_large_app_name,
  my_var: "MY ENV VARIABLE"

and then in your code

Application.get_env(:my_large_app_name, :my_var)

WARNING: as @José Valim said you can not set any name as key :my_large_app_name it have to be the same of your project