Skip to content

Instantly share code, notes, and snippets.

@db0sch
Last active July 30, 2024 12:59
Show Gist options
  • Save db0sch/19c321cbc727917bc0e12849a7565af9 to your computer and use it in GitHub Desktop.
Save db0sch/19c321cbc727917bc0e12849a7565af9 to your computer and use it in GitHub Desktop.
How to regenerate the master key for Rails 5.2 credentials

If your master.key has been compromised, you might want to regenerate it.

No key regeneration feature at the moment. We have to do it manually.

  1. Copy content of original credentials rails credentials:show somewhere temporarily.
  2. Remove config/master.key and config/credentials.yml.enc
  3. Run EDITOR=vim rails credentials:edit in the terminal: This command will create a new master.key and credentials.yml.enc if they do not exist.
  4. Paste the original credentials you copied (step 1) in the new credentials file (and save + quit vim)
  5. Add and Commit the file config/credentials.yml.enc

Important

  • Make sure config/master.key is listed in .gitignore and NOT tracked by git.
  • The command EDITOR=vim rails credentials:edit might not work if you require credential value in some file (initializers or database.yml). I had the problem with devise.rb. I just uncommented the line secret_key = ... just the time to run the command to regenerate the credentials file, and then commented the line out again.
  • If you want to use Sublime to edit the credentials, you can replace the command EDITOR=vim rails credentials:edit by EDITOR="/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl -w" rails credentials:edit

source: https://blog.eq8.eu/til/rails-52-credentials-tricks.html

@alex59495
Copy link

alex59495 commented Feb 26, 2021

Thanks for sharing !

@scottbarrow
Copy link

scottbarrow commented Apr 27, 2022

for step 3, set config.require_master_key = false in application.rb or production.rb otherwise an exception will be raised since a key is required to edit credentials with this set to true

@db0sch
Copy link
Author

db0sch commented Apr 28, 2022

@scottbarrow is this a new behaviour in rails 7?
In previous versions, the master key was re-generated automatically. But maybe this has changed

@scottbarrow
Copy link

ah yeah very well could be, the code does look different

@immakdas
Copy link

thanks for sharing this

@Georgy5
Copy link

Georgy5 commented Mar 19, 2023

Thank you, this helped me out today 👍

@iseitz
Copy link

iseitz commented Oct 4, 2023

Thank you! saved me hours of hair-pulling and figuring out the workaround 👍

@Forison
Copy link

Forison commented Jul 30, 2024

I have a similar issue, but in my case the master.key is never generated on crendential.yml.en is created, can anyone help me? I am using rails 6.1.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment