Failing to access environment variables within `da

2019-01-13 00:18发布

问题:

I have the following developement section of my development.yml file:

development:
  adapter: postgresql
  host: localhost
  database: testtb
  username: app_user
  password: ENV['APP_USER_POSTGRES_PASSWORD']     <= Troublesome line

When I open a rails console via bundle exec rails console and type ENV['APP_USER_POSTGRES_PASSWORD'] I get back the DB password I've specified in my local profile. However, when I start my rails server, it can't connect to the DB, failing with

PGError FATAL:  password authentication failed for user "app_user"

This was previously working when I had the DB password actually typed out in plain text, rather than trying to access it via ENV['...'], but for obvious reasons I want to keep the actual password out of this file entirely (and therefore out of the code repository) while still being able to commit other, non-secure changes to the database.yml file.

Is there something special about the syntax I'm missing, or are the environment variables for some reason not available when the database.yml file is being loaded?

回答1:

Update: Some people report in the comments that this doesn't work as of Rails 4.2.x.x. I haven't tried it myself, so YMMV.


Ah, finally figured out the simple solution - it accepts embedded Ruby:

password: <%= ENV['APP_USER_POSTGRES_PASSWORD'] %>


回答2:

Short and quick solution if you are running a newer Rails version! Run the following command:

spring stop

..then run rails console or other rails command. My issue was that Spring server needed to be restarted in order to refresh/pickup my new ENV vars. I was starting up Rails console and it couldn't see them until I shut down Spring.

Previous versions of Rails didn't have this issue since they didn't use Spring server.

Another tool to help you troubleshoot -- Use the following command to print out your database.yml config. You can run it from the command line, but I prefer to run this within Rails console since then you can use awesome_print to make it pretty:

Within rails console:

puts ActiveRecord::Base.configurations

...or using awesome_print

ap ActiveRecord::Base.configurations

Or instead from the command line:

bin/rails runner 'puts ActiveRecord::Base.configurations'