Failing to access environment variables within `database.yml` file

Ruby on-RailsEnvironment VariablesYamlRuby on-Rails-2

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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'] %>

Solution 2 - Ruby on-Rails

Short and quick solution if you are running a Rails version > 4.2 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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeffluntView Question on Stackoverflow
Solution 1 - Ruby on-RailsjeffluntView Answer on Stackoverflow
Solution 2 - Ruby on-RailsFireDragonView Answer on Stackoverflow