---
title: "Rails 6 adds support for Multi Environment credentials"
description: "Rails 6 adds support for multi environment credentials"
canonical_url: "https://www.bigbinary.com/blog/rails-6-adds-support-for-multi-environment-credentials"
markdown_url: "https://www.bigbinary.com/blog/rails-6-adds-support-for-multi-environment-credentials.md"
---

# Rails 6 adds support for Multi Environment credentials

Rails 6 adds support for multi environment credentials

- Author: Berin Larson
- Published: July 3, 2019
- Categories: Rails 6, Rails

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](https://github.com/rails/rails/pull/33521#issuecomment-449403068).

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

```bash
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.

```yaml
aws:
  access_key_id: "STAGING_KEY"
```

We can then access the access_key_id in staging environment.

```ruby

>> 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](https://github.com/rails/rails/pull/33521#issuecomment-412382031)
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.

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

```ruby

>> 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](https://github.com/rails/rails/pull/33521)

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-adds-support-for-multi-environment-credentials)
