Ruby on Rails: Accessing application credentials
How to manage and access Rails credentials safely in your application
Ruby on Rails: Accessing application credentials
Adding and editing credentials
We open the credentials file like so:
1
EDITOR="code --wait" rails credentials:edit -e development
Rails will create a new config/master.key file and config/credentials.yml.enc. Keep the master key safe, because anyone with access can decrypt your credentials.
Then we can edit the keys and values:
1
2
recaptcha:
site_key: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
When we are done, we close the file and it gets encrypted.
How to access them in the app:
The right way:
1
secret_key = Rails.application.credentials.dig(:recaptcha, :secret_key_v3))
We use .dig, because if the credentials are missing/empty it will return nil, instead of crashing:
1
secret_key = Rails.application.credentials.dig[:recaptcha][:secret_key_v3]
If recaptcha is missing from credentials.yml, then this will return an undefined method '[]' for nil:NilClass (NoMethodError)
Sources
This post is licensed under CC BY-NC 4.0 by the author.