Rails 6 adds support for Multi Environment credentials

Berin Larson

Berin Larson

July 3, 2019

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

Rails 6.0.0.beta3

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

rails 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.

aws:
  access_key_id: "STAGING_KEY"

We can then access the access_key_id in staging environment.


>> RAILS_ENV=staging rails c

pry(main)> Rails.application.credentials.aws[:access_key_id]

=> "STAGING_KEY"

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.

aws:
  access_key_id: "DEFAULT_KEY"
stripe:
  secret_key: "DEFAULT_SECRET_KEY"

>> RAILS_ENV=staging rails c

pry(main)> Rails.application.credentials.aws[:access_key_id]

=> "STAGING_KEY"

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.