What is the Rails Master Key?

The Rails master key is a crucial component of the Rails credentials system introduced in Rails 5.2. It’s used to encrypt and decrypt sensitive information stored in the credentials file, ensuring that sensitive data like API keys and passwords are not exposed in your version control system.

Key Points

  • The master key is typically stored in config/master.key
  • It should never be committed to version control
  • Rails uses this key to decrypt config/credentials.yml.enc
  • If lost, you’ll need to regenerate both the master key and the credentials file

Where to Find the Master Key

  1. Default Location: config/master.key
  2. Environment Variable: Rails also checks for RAILS_MASTER_KEY environment variable

How to Regenerate the Master Key

  1. Delete Existing Files: Remove both config/master.key and config/credentials.yml.enc if they exist.
  2. Generate New Credentials: Run the following command in your terminal:
    EDITOR="vim" bin/rails credentials:edit
  3. Verify Creation: Check that config/master.key and config/credentials.yml.enc now exist
  4. Update .gitignore: Ensure config/master.key is listed in your .gitignore file

Important Considerations

  • After regenerating, all previous encrypted credentials will be lost
  • You’ll need to re-add any sensitive information to the new credentials file
  • Share the new master key securely with team members who need it

How to access credentials in your Rails app:

Rails.application.credentials.some_api_key

Best Practices

  • Never commit the master key to version control
  • Use environment-specific credentials for different environments
  • Rotate the master key periodically for enhanced security

Support On Demand!

Ruby on Rails