Developers always want to keep their credentials safe. But they need to share it internally while development and it is possible that credentials can be made public mistakenly.

To make our old secrets.yml more secure Rails core team introduced Encrypted credentials in Rails 5.1.

In Rails 5.1 there were two files secrets.yml.enc and secrets.yml and it was creating confusion for our beloved SECRET_BASE_KEY. To remove this dilemma Rails core team decided to remove those two files and having only one file where you can store your all secret stuff like AWS key, database password, API keys and whatever which you want to make secret from the outside world and even from you!

So, lets see how to have this encrypted file, how to manage it, how to edit it and how to access it in your project.

As encrypted credentials shipped with rails you have to install this version of rails. You can do it using this command:

gem install rails --pre --no-ri --no-rdoc

After installing rails 5.2 create new project using this version and you will see two files in config folder config/master.key and config/credentials.yml.enc. You can share master.key with your team but don’t check into shared repository. Rails will be automatically adding it to .gitignore file for you. master.key is the key which is necessary to de-crypt encrypted credentials. The encrypted credentials are saved on config/credentials.yml.enc.

Now, you might have questioned how to edit credentials.yml.enc? You can not directly edit this file as all credentials are in encrypted form. You have to use the command rails credentials:edit to edit them. You can do it using your favorite editor too. Here I am using Sublime.

EDITOR="subl --wait" bin/rails credentials:edit

Now you can edit your credentials in yaml format like we were doing in older version of rails for secrets.yml.

You can access the credentials anywhere in your application with Rails.application.credentials.key_name The biggest advantage I can see of encrypted credentials is you can push this file to git and you can have the track of history now.

Thank you for reading!

Click here for more details…

At BoTree Technologies, we build enterprise applications with our RoR team of 25+ engineers.

We also specialize in Python, RPA, AI, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!