Rails 5.1 - Introduction to Encrypted Secrets YML (Credentials)
Rails applications generally interact with multiple services, including but not limited to services, payment gateways, and oAuth. After all, they are called secrets for a reason, and it is of utmost importance that these secrets remain secret.
In Rails 3 and Rails 4.0, developers used environment variables to store credentials. Rails 4.1 introduced secrets.yml to host credentials used by the application. Rails 5.1 introduces encrypted credentials.
The main advantage of encrypted credentials is that it is safe to include with the source code. This way you won't end up in a state where the secrets.yml
file is out of date. The encrypted file is decrypted by Rails using the secret key. The secret key, as the name suggests, should remain secret. It is also essential that you not lose this key or have issues running the application.
This blog post describes how you can enable encrypted credentials on Rails 5.1.
Configure Encrypted Credentials
The first step would be to run the setup process.
rails secrets:setup
This process will create two files.
secrets.yml.enc
is the encrypted file that contains all of our credentials. This file is safe to commit to git. Given the presence of the key, you can access the secrets throughRails.application.secrets
.secrets.yml.key
is the encryption key. The setup process will add this file to the gitignore file.
Configuring The Credential Editor
We are no longer going to have a plain text credentials file. How do we add credentials to the encrypted file? The task of editing the file and encrypting it is taken care of by the rails secrets:edit
command. However, you should specify your prefered editor. Mine is vim. I will add it to my bash profile or zsh profile.
export EDITOR=vim
Now when you run rails secrets:edit
, it will open the file in vim.
Adding Credentials
Now the setup process is complete. All you have to do is add secrets to the editor that opens when you run rails secrets:edit
. When you save and quit, the config/secrets.yml.enc
will be updated.
If you are upgrading from Rails 5, you can copy your present secrets.yml file and paste it on this editor.
Configuring Environments
Since it is a new feature, it is not enabled by default. Add these lines to your environments config/environments/development.rb
, config/environments/test.rb
and config/environments/production.rb
.
config.read_encrypted_secrets = true
That's it. Open up a console and see that it works.
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.