Rails 5.2 Encrypted credentials for production environment

Aravind picture Aravind · Jun 27, 2018 · Viewed 7.9k times · Source

I have created the new Rails app with the version of 5.2. Rails 5.2 introduced the encryption feature for the secrets.

I have configured the secret key in devise.rb file

config.secret_key = Rails.application.credentials[Rails.env.to_sym][:secret_key_base]

and also added the secret_key's for all environments using

EDITOR=vim rails credentials:edit

development:
 secret_key_base: absdss

test:
 secret_key_base: 123232

production:
 secret_key_base: 123456

after the saving the credentials i can able to get the secret_key's in the rails console in local

Output in rails console:

Running via Spring preloader in process 44308
Loading development environment (Rails 5.2.0)
2.5.1 :001 > Rails.application.credentials.development[:secret_key_base]
=>     "absdss" 

The credentials are not working on production server, we are using CI/CD in gitlab for deployment stages, when i run the

rails db:create db:migrate

i am getting the following error

> rails db:create db:migrate

 ---> Running in 1563453ddf2a

rails aborted!

NoMethodError: undefined method `[]' for nil:NilClass

/usr/src/app/config/initializers/devise.rb:12:in `block in <main>'

/usr/local/bundle/gems/devise-4.4.3/lib/devise.rb:307:in `setup'

/usr/src/app/config/initializers/devise.rb:5:in `<main>'

/usr/local/bundle/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'

Now the question is how to set the RAILS_MASTER_KEY to production server?

Answer

praaveen V R picture praaveen V R · Jun 27, 2018

Im sharing few points which may help you

Encrypted credentials offer a few advantages over plaintext credentials or environment variables

Rails 5.1 introduced encrypted secrets

config/secrets.yml.key
config/secrets.yml.enc

Rails 5.2 replaces both secrets with encrypted credentials

config/credentials.yml.enc
config/master.key

config/master.key file is created while creating a rails project

Encryption key(master.key) is git ignored

In production

config/environments/production.rb

config.require_master_key = true

Can’t decrypt your credentials without the key

Managing the Key

a. scp or sftp the file

b. If you need to give a developer a copy of the key then You can use a password manager because they use encryption.

c. I used last pass for managing the master key file

The key used to encrypt credentials is different from the secret key base.

The key on master.key is used to encrypt and decrypt all credentials. It does not replace the secret key base.

The secret key base is required by Rails. If you want to generate a new secret key base run,

bin/rails secret

and add that to your credentials by running bin/rails credentials:edit.