50

In my settings.yml file I have several config vars, some of which reference ENV[] variables.

for example I have ENV['FOOVAR'] equals WIDGET

I thought I could reference ENV vars inside <% %> like this:

Settings.yml:

default:
   cv1: Foo
   cv2: <% ENV['FOOVAR'] %>

in rails console if I type

> ENV['FOOVAR']
=> WIDGET

but

> Settings.cv1
=> Foo   (works okay)
> Settings.cv2
=>nil   (doesn't work???)
j0k
  • 22,600
  • 28
  • 79
  • 90
jpw
  • 18,697
  • 25
  • 111
  • 187
  • 2
    You might want to checkout this guide about configuration, and local variables : http://railsapps.github.io/rails-environment-variables.html tl;dnr: figaro gem can be useful for that. – Antzi May 02 '13 at 10:36

4 Answers4

71

use following:-

 default:
       cv1: Foo
       cv2: <%= ENV['FOOVAR'] %>
Anubhaw
  • 5,978
  • 1
  • 29
  • 38
  • 7
    This doesn't work if you dont add the .yml as .yml.erb file and add the code `template = ERB.new File.new("path/to/config.yml.erb").read processed = YAML.load template.result(binding)' – Faz Mar 15 '16 at 16:13
  • @Faz also works if loading the file from app/config via `Rails.application.config_for()` – Cody Crumrine Feb 21 '23 at 17:33
31

The above solution did not work for me. However, I found the solution on How do I use variables in a YAML file?

My .yml file contained something like:

development:
gmail_username: <%= ENV["GMAIL_USERNAME"] %>
gmail_password: <%= ENV["GMAIL_PASSWORD"] %>

The solution looks like:

template = ERB.new File.new("path/to/config.yml.erb").read
processed = YAML.load template.result(binding)

So when you introduce a scriptlet tag in .yml file, it is more of erb template. So read it as a erb template first and then load the yml as shown above.

Community
  • 1
  • 1
arpiagar
  • 4,314
  • 1
  • 19
  • 12
24

Use <%= ENV['FOOVAR'] %> instead of <% ENV['FOOVAR'] %>.

Be aware that this approach will only work if whatever is parsing the Yaml file is set up to process it via Erb (for example, you can see how Mongoid does exactly this). It's not universally supported in Yaml files though, so it depends on what you're using this Yaml file for.

PreciousBodilyFluids
  • 11,881
  • 3
  • 37
  • 44
0

I was able to resolve this with simple code

data = {}
YAML.load_file("path_of_file/settings.yml").each do |key, value|
  data[key] = ENV[value] || value
end 

where my data was something like this

account: ACCOUNT_USERNAME
password: ACCOUNT_PASSWORD
port: 5002

and ACCOUNT_USERNAME and ACCOUNT_PASSWORD are environment variables

Realms AI
  • 101
  • 4
  • It is not a reliable solution. It may lead to some unexpected and hard-to-catch behavior when any value in the .yml file accidentally matches one of the environment variables. And you never know in which environment the application will run in the future. It's better to explicitly specify places where ENV variables are expected and use ERB parser. – Alexey Grinko Sep 24 '20 at 16:38