Goodbye Secrets. Welcome Credentials!
Secrets were introduced with Ruby on Rails 5.1 to make life easier for developers who need to store encrypted credentials or API keys in their repository. Many people were confused by the way it had to be done. It did include a couple of extra steps and an often unnecessary seperation of different environments. I have no opinion about this but I do agree that the new way of achieving it in Ruby on Rails 5.2 is a lot easier. DHH got rid of the
secrets and introduced
credentials (read his PR for more information).
Kudos to DHH and the core team for doing this. Most projects would have stick with the old way because it was kind of ok.
Once you installed Rails 5.2 each of your new Rails projects has an already good to go setup for using credentials. No more generating keys manually. The important master key is automatically generated and stored in the file
config/master.key which can be shared with other developers in the team but which should never be checked into the Git repository. The default
.gitignore has been updated accordingly:
# Ignore master key for decrypting credentials and more.
All credentials are stored encrypted in the file
config/credentials.yml.enc. Obviously you can not edit the file directly. You have to use the command
rails credentials:editto edit them. For that to work you have to set the shell environment variable
EDITOR first. Or you can do both with this one liner in your Bash shell:
$ EDITOR=vim rails credentials:edit
Now you can edit your credentials in
yaml format. In this example I add a credential with the name foobar and the value test:
# access_key_id: 123
# secret_access_key: 345# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
You can access a credential anywhere in your application with
AppName::Application.credentials.name_of_the_credential. An example from within the console:
$ rails console
Running via Spring preloader in process 19662
Loading production environment (Rails 5.2.0)
If you like this post I’d like to ask you for a favour:
Create an account at my open-source business network https://www.vutuv.de
Thank you and see you there!
To use the credentials in production you have to copy the
config/master.keyfile to your production environment or setting it up with an environment variable.
I’m a big fan of screencasts too. So here it is:
In case you need on site Ruby on Rails training:
Please send me an email to email@example.com
I’m currently working on my new Ruby on Rails 5.2 book. You can follow me on Twitter to get updates too: https://twitter.com/wintermeyer
In case you speak German: https://www.wintermeyer-consulting.de