ruby-on-railsenvironment-variablesyamlruby-on-rails-2

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


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?


Solution

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