This blog is part of our Rails 6 series. Rails 6.0.0.rc1 was recently released.

In Rails 5.2, encrypted credentails 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

Rails 6.0.0.beta3

If we want to add credentials to be used in staging environment, we can run

rails edit:credentials --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.

  access_key_id: "STAGING_KEY"

We can then access the access_key_id in staging environment.

>> RAILS_ENV=staging rails c



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.

  access_key_id: "DEFAULT_KEY"
  secret_key: "DEFAULT_SECRET_KEY"
>> RAILS_ENV=staging rails c



pry(main)> Rails.application.credentials.stripe[:secret_key]

Traceback (most recent call last):
        1: from (irb):6
NoMethodError (undefined method `[]' for nil:NilClass)

Here is the relevant pull request