Platform.sh部署Rails项目时缺失RAILS_MASTER_KEY导致部署失败的问题咨询
部署场景与报错说明
报错信息:
W: 缺少用于解密文件的加密密钥,请向团队获取主密钥,将其写入/app/config/master.key,或配置至ENV['RAILS_MASTER_KEY']。
在Platform.sh上部署Rails项目时,因缺少解密密钥导致部署操作失败。
现有配置梳理
- 本地开发环境配置:在Ubuntu
.bashrc文件中已配置本地环境变量export RAILS_MASTER_KEY='ad5e30979672cdcc2dd4f4381704292a' - Rails生产环境配置:
config/environments/production.rb中已开启强校验config.require_master_key = true - 项目Platform.sh相关配置文件:
.platform.app.yaml
# The name of this app. Must be unique within a project. name: app type: 'ruby:2.7' # The size of the persistent disk of the application (in MB). disk: 5120 mounts: 'web/uploads': source: local source_path: uploads relationships: postgresdatabase: 'dbpostgres:postgresql' hooks: build: | gem install bundler:2.2.5 bundle install RAILS_ENV=production bundle exec rake assets:precompile deploy: | RACK_ENV=production bundle exec rake db:migrate web: upstream: socket_family: "unix" commands: start: "\"unicorn -l $SOCKET -E production config.ru\"" locations: '/': root: "\"public\"" passthru: true expires: "24h" allow: trueroutes.yaml
# Each route describes how an incoming URL is going to be processed by Platform.sh. "https://www.{default}/": type: upstream upstream: "app:http" "https://{default}/": type: redirect to: "https://www.{default}/"services.yaml
# The name given to the PostgreSQL service (lowercase alphanumeric only). dbpostgres: type: postgresql:13 # The disk attribute is the size of the persistent disk (in MB) allocated to the service. disk: 5120 db: type: postgresql:13 disk: 5120 configuration: extensions: - pgcrypto - plpgsql - uuid-ossp
问题根因
本地.bashrc配置的环境变量仅对本地终端的开发场景生效,Platform.sh的独立部署运行环境不会读取你本地的shell配置文件。同时Rails项目默认会在.gitignore中排除config/master.key文件,避免加密密钥随代码仓库泄露,因此部署流程走到Rails初始化阶段时,既读不到磁盘上的master.key文件,也获取不到对应的环境变量,最终触发解密失败报错。
解决步骤
- 核心方案(推荐):通过Platform.sh原生环境变量配置注入主密钥,避免密钥明文泄露
- 登录Platform.sh对应项目,进入当前部署环境的变量配置页面
- 新增自定义环境变量:
- 变量名:
RAILS_MASTER_KEY - 变量值:和本地一致的主密钥
ad5e30979672cdcc2dd4f4381704292a - 必须勾选变量生效范围覆盖「构建阶段+运行阶段」,否则build钩子中执行
assets:precompile时,Rails依然会因为找不到主密钥报错 - 建议开启“变量值加密不可见”选项,避免密钥在控制台明文展示
- 变量名:
- 配置完成后重新触发部署流程即可,不需要修改现有hooks命令,Rails会自动读取注入的环境变量完成解密
- 临时验证方案(不推荐长期使用):
在.platform.app.yaml的build、deploy钩子脚本开头临时追加密钥导出命令,例如:
注意该方式会把明文密钥写入git跟踪的配置文件,存在泄露风险,仅适合临时调试hooks: build: | export RAILS_MASTER_KEY='ad5e30979672cdcc2dd4f4381704292a' gem install bundler:2.2.5 bundle install RAILS_ENV=production bundle exec rake assets:precompile deploy: | export RAILS_MASTER_KEY='ad5e30979672cdcc2dd4f4381704292a' RACK_ENV=production bundle exec rake db:migrate - 额外校验项:
- 确认项目
.gitignore规则中已排除config/master.key,不要把该文件提交到代码仓库 - 不需要手动在服务器磁盘上创建
/app/config/master.key文件,通过环境变量注入的方式Rails原生支持自动读取,无需额外写文件逻辑
- 确认项目
内容的提问来源于stack exchange,提问作者kamate vakaramoko
相关产品推荐
相关产品推荐

