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.
Accessing credentials in code
1
Rails.application.credentials.dig(:recaptcha, :secret_key_v3)
We use .dig
, because it will return nil
if the keys are missing and the app won’t break.
This post is licensed under CC BY-NC 4.0 by the author.