Rails 5.2 How to use the new Credentials Api

To help rails development teams manage credentials, Rails 5.2 introduces a new Credentials Api. Credentials are stored in a file called config/credentials.yml.enc in an encrypted form, so they are safe to be committed to source control. This eliminates the pain of synchronizing modified keys across the team.

The file that should not be tracked by Git under any circumstances (and is already listed in .gitignore for new Rails 5.2 projects) is config/master.key. It contains the autogenerated key that allows to decrypt your credentials. As documentation warns us:

Don’t lose this master key! Put it in a password manager your team can access. Should you lose it no one, including you, will be able to access any encrypted credentials.

Edit credentials

So how do you edit your credentials, if the file containing them is always encrypted? Rails 5.2 has a new task for that:

$ rails credentials:edit

This command will open your default editor with a plain text file where you can put your keys in key_name: key_value format. YAML nesting is also permitted. You can then access your credentials with:

Rails.application.credentials.key_name

or, if you use nested keys:

Rails.application.credentials.dig(:section_name, :nested_key_name)

Once you save and close the temporary file, its contents will be encoded into config/credentials.yml.enc.

List credentials

You can also print your keys to Terminal with:

$ rails credentials:show

Now, provided that all members of your team have the same master.key file, you can safely collaborate through Git and not be afraid of exposing sensitive information ever again.

Production

For production, you will need to set a single RAILS_MASTER_KEY environment variable.

Note: In order to get credentials to work with an external editor like Atom, you need to call the task with EDITOR="atom --wait" credentials:edit. Or use a shell editor, that may be more suitable for quickly editing a few keys: EDITOR=vi credentials:edit.