Search code examples
ruby-on-railsruby-on-rails-4rake

rake not seeing Rails.application.secrets


In short:

  1. seems that rake does not have access to Rails.application.secrets in config/database.yml file
  2. what is the purpose of config/secrets.yml then?

In long:

When I run

RAILS_ENV=production rake db:migrate

I get the error Mysql2::Error: Access denied for user 'root'@'localhost' (using password: NO), though I specified appropriate values in config/database.yml and the user connecting should not be 'root'. This is an excerpt from respective config files:

# config/database.yml
production:
  <<: *default
  adapter: mysql2
  host: localhost
  database: <%= Rails.application.secrets[:database][:name] %>
  username: <%= Rails.application.secrets[:database][:username] %>
  password: <%= Rails.application.secrets[:database][:password] %>

# config/secrets.yml
production:
  secret_key_base: very-long-blah-blah-blah
  database:
    name: app_db_name
    username: app_db_user
    password: app_db_password

Seems that rake has no access to Rails.application.secrets. Running migration succeeds when I explicitly put necessary values in database.yml, for example, as follows:

production:
  <<: *default
  adapter: mysql2
  host: localhost
  database: <%= Rails.application.secrets[:database][:name]  || 'app_db_name' %>
  username: <%= Rails.application.secrets[:database][:username] || 'app_db_user' %>
  password: <%= Rails.application.secrets[:database][:password] || 'app_db_password' %>

The above proves that Rails.application.secrets[:database][:name] resolves to nothing.

How to have access to Rails.application.secrets in rake? Would this be the correct solution?

I know that I can use ENV[VARNAME] to fill in secret sections of config/database.yml. But what the the purpose of config/secrets.yml file then?

Moreover, I am using Passenger, which means that variables in .bashrc will probably not be accessible to the web server (I had this issue with secret_key_base). Therefore I try to avoid using environment variable. Just do not want to have all my secrets spilled all over the server.

rails-4.2.2, Ubuntu LTS 14.04


Solution

  • I haven't seen such nested content for the secrets.yml like you have, also the release notes doesn't have such kind. You should be just fine with the below code

    # config/secrets.yml
    production:
      secret_key_base: very-long-blah-blah-blah
      name: app_db_name
      username: app_db_user
      password: app_db_password
    

    And in the database.yml

    # config/database.yml
    production:
      <<: *default
      adapter: mysql2
      host: localhost
      database: <%= Rails.application.secrets.name %>
      username: <%= Rails.application.secrets.username %>
      password: <%= Rails.application.secrets.password %>