/ RAILS

Rails 6 supports Multi Environment Credentials

Rails 6 adds support for multi environment credentials. Rails 5.2 includes encrypted credentials for Rails applications.

Rails 5.1 had introduced a feature of secret management in Rails applications It has been evolved and renamed since then to encrypted credentials. But, it had support to have single encrypted credentials file.

Now, we can have environment specific credentials with Rails 6.

Add new environment credentials

To add credentials for a staging environment, we can run the command given below.

rails credentials:edit --environment staging

This will create a file config/credentials/staging.yml.enc.

Notes

  • Rails will detect environment specific credentials file based on the file format given above
  • Environment specific file will take precedence over default config/credentials.yml.enc file

Support in Rails 5.2

We can still support environment specific credentials in older Rails application. As suggested in a Github comment, we can override credentials method on Rails application to achieve this.

module YourAppModule
  class Application < Rails::Application
    def credentials
      if Rails.env.production?
        super
      else
        encrypted(
          "config/credentials.#{Rails.env.downcase}.yml.enc",
          key_path: "config/#{Rails.env.downcase}.key"
        )
      end
    end
  end
end

As we can see, this uses default credentials file config/credentials.yml.enc if the Rails environment is production. It uses environment specific encrypted file if the environment is non production environment.

Reference

  • Pull Request: Add support for multi environment credentials.
akshay

Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee