Rails 5.2 introduced so many nice things, and encrypted credentials are one them. The idea behind all this is to ease handling of your secrets in software. This article will walk you thru how to use this new nice feature of Rails.
When you create a new Rails 5.2 project with
rails new command Rails will generate
master.key which is used to encrypt and decrypt your credentials. You can find this file from the
Your encrypted credentials are kept in
credentials.yml.enc which is encrypted with your
master.key. Quite straightforward, isn't it?
Contents of the credentials file
credentials.yml.enc is encoded you shouldn't touch it with any editor directly, instead, you run
rails credentials:edit. This may end up to error if you haven't set any editor, an error might look like this:
No $EDITOR to open file in. Assign one like this: EDITOR="mate --wait" bin/rails credentials:edit
I prefer to use pico as an editor so, I would run my command as:
EDITOR=/usr/bin/pico rails credentials:edit
Most editors will need
--wait flag to make sure encryption happens after the editor is closed.
Once your editor is open, you will see example credential file. Add all your secrets here, and they are safe. Once you have saved your file, rails will encrypt your credentials with
Important: Once your credentials are encrypted, do not delete, change or lose your master.key. It's the only way to decrypt credentials.
After you have done changes to
credentials.yml.enc you can open it and notice data is saved in YAML format. You can easily test your credentials with
rails console. For example we can read AWS Access Key ID credentials (if you commented out example lines in credentials) with
People have different opinions about how you should work with your
master.key. Some say you can include it to your repository, but I strongly disagree on that since if it's there it's also possible to see credentials. One of my strict rules is that you should never ever save any credentials with your source code unless it's test data which doesn't work anywhere in the real world.
I strongly advise you to add
config/master.key to your
.gitignore file and keep your
master.key somewhere safe.
How to use in production
I personally like to use Heroku on my projects, so this is how you do it with Heroku. Although it will work the same way in other environments, except you don't you Heroku CLI then in that case :)
Since we don't want
master.key to be part of your deployed code we need to deliver contents of that file some other way. That way would be via environment variables.
Name for environment variable is
RAILS_MASTER_KEY and it should be set to contents of your
config/master.key. With Heroku this can be done directly from Heroku CLI:
heroku config:set RAILS_MASTER_KEY=YOUR-KEY
Or from the Heroku dashboard.
Now all your secrets are in one safe place, just remember to keep your master.key somewhere safe :)