This blog is part of our Rails 6 series.
In Rails 5.2, encrypted credentials are stored in the file config/credentials.yml.enc. This is a single flat file which is encrypted by the key located in config/master.key.
Rails 5.2 does not support storing credentials of different environments with different encryption keys. If we want environment specific encrypted credentials, we'll have to follow this workaround.
Rails 6 has added support for Multi Environment credentials. With this change, credentials that belong to different environments can be stored in separate files with their own encryption key.
Let's see how this works in Rails 6.0.0.beta3
If we want to add credentials to be used in staging environment, we can run
1rails credentials:edit --environment staging
This will create the credentials file config/credentials/staging.yml.enc and a staging specific encryption key config/credentials/staging.key and open the credentials file in your text editor.
Let's add our AWS access key id here.
1aws: 2 access_key_id: "STAGING_KEY"
We can then access the access_key_id in staging environment.
1 2>> RAILS_ENV=staging rails c 3 4pry(main)> Rails.application.credentials.aws[:access_key_id] 5 6=> "STAGING_KEY" 7
Which takes precedence: Global or Environment Specific credentials?
Credentials added to global file config/credentials.yml.enc will not be loaded in environments which have their own environment specific credentials file (config/credentials/$environment.yml.enc).
So if we decide to add the following to the global credentials file, these credentials will not be available in staging. Since we already have a environment specific credentials file for staging.
1aws: 2 access_key_id: "DEFAULT_KEY" 3stripe: 4 secret_key: "DEFAULT_SECRET_KEY"
1 2>> RAILS_ENV=staging rails c 3 4pry(main)> Rails.application.credentials.aws[:access_key_id] 5 6=> "STAGING_KEY" 7 8pry(main)> Rails.application.credentials.stripe[:secret_key] 9 10Traceback (most recent call last): 11 1: from (irb):6 12NoMethodError (undefined method `' for nil:NilClass) 13
Here is the relevant pull request