Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
like image 550
Sheharyar Avatar asked Jun 23 '15 06:06

Sheharyar


People also ask

How do you find the variable value of an environment?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do you get an environment variable in Elixir?

Now we are going to use environment variables to better understand how Elixir config works during runtime. First, update config/runtime. exs to get the WELCOME environment variable from the system using System. fetch_env/1.


2 Answers

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]
like image 170
Sheharyar Avatar answered Sep 20 '22 15:09

Sheharyar


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

like image 33
douarbou Avatar answered Sep 17 '22 15:09

douarbou