Heroku部署Rails应用时遭遇RAILS_MASTER_KEY错误求助
Hey there, let's work through this issue you're facing with your Rails app on Heroku step by step.
First, let's break down the initial error you ran into:
Running: rake assets:precompile
rake aborted!
Rails::Secrets::MissingKeyError: Missing encryption key to decrypt secrets with. Ask your team for your master key and put it in ENV["RAILS_MASTER_KEY"]
This error pops up because Rails uses a local encryption key (stored in config/master.key) to unlock your encrypted config/secrets.yml.enc file. Heroku doesn't have access to your local master.key file by default, so it throws this error until you pass the key via the RAILS_MASTER_KEY environment variable.
Why using rake secret caused a new problem
When you generated a new key with rake secret and set it as RAILS_MASTER_KEY, you created a totally fresh random key—but this key doesn't match the one that was used to encrypt your existing secrets.yml.enc file. Heroku tries to decrypt the file with this mismatched key, which fails, leading to a new set of issues (like decryption failures or missing critical secrets).
The Correct Fix Steps
Let's get this sorted properly:
Grab your actual local master key
- Open the
config/master.keyfile on your local machine (this file should be in your.gitignore, so it's never committed to Git). The string inside this file is the exact key you need. - If you've lost this file, check if you previously set a
RAILS_MASTER_KEYenvironment variable on your local machine—you can pull the value from there.
- Open the
Set the correct key on Heroku
- Using the Heroku CLI: Run this command in your terminal, replacing
your-real-master-key-valuewith the string from your localmaster.key:heroku config:set RAILS_MASTER_KEY=your-real-master-key-value - Or via the Heroku Dashboard: Go to your app's Settings page, find the "Config Vars" section, add a new variable named
RAILS_MASTER_KEYand paste your local master key as the value.
- Using the Heroku CLI: Run this command in your terminal, replacing
If you need to regenerate a master key (only if the original is lost forever)
If you can't recover the original master key, you'll need to reset your secrets setup:- Delete the existing
config/master.keyandconfig/secrets.yml.encfiles - Run
rails secrets:setupto generate a new master key and empty encrypted secrets file - Edit
config/secrets.ymlto add your app's sensitive data (like API keys, database credentials) - Run
rails secrets:encryptto encrypt your updated secrets file - Set this new master key as the
RAILS_MASTER_KEYon Heroku using the steps above
- Delete the existing
Important Notes
- Never commit
config/master.keyto version control—keep it in your.gitignoreto avoid exposing sensitive data. rake secretgenerates a random key for general use (like session secrets), but it's not a replacement for theRAILS_MASTER_KEYthat decrypts your encrypted secrets file.
内容的提问来源于stack exchange,提问作者Haris Uddin

