Search code examples
amazon-s3credentialsruby-on-rails-5.2

Cannot access :development or :production credentials with [Rails.env]


I am upgrading an app to Rails 5.2.0 and trying to create the credentials.yml.enc file so I can access a different :aws bucket for both :development and :production environments.

I am following this tutorial.

My credentials.yml.enc

development:
  aws:
    access_key_id: 123dev
    secret_access_key: 345dev
    bucket: development_bucket

production:
  aws:
    access_key_id: 123pr
    secret_access_key: 345pr
    bucket: production_bucket

aws:
  access_key_id: long_hexidecimal_string
  secret_access_key: longer_hexidecimal_string

In console, if I type Rails.application.credentials[:aws][:access_key_id] then I get the expected output: long_hexidecimal_string

But when I type Rails.application.credentials[Rails.env][:aws][:access_key_id] I get this error: NoMethodError: undefined method []' for nil:NilClass

Testing to see if problem is in the yml file, I tried this and got the expected result:

irb(main):015:0> Rails.application.credentials[:development][:aws][:access_key_id]
=> "123dev" 

I think the problem is [Rails.env] yields ["development"], not [:development]. Is there an easy way to symbolize the the [Rails.env] output? I'm hoping for [Rails.env.symbolize!] but that doesn't work.


Solution

  • I should have spent more time googling rather than typing up this question.

    irb(main):016:0> Rails.application.credentials[Rails.env.to_sym][:aws][:access_key_id]
    => "123dev"
    

    I hope this helps someone one day!