Rails 7: validate_secret_key_base': 缺少 'production' 环境下的 `secret_key_base`。

4

Rails 7.0.4

使用 MRSK 部署时,我遇到了这个错误

[linux/arm64 build 10/10] RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile: #23 1.053 rails aborted! #23 1.053 ArgumentError: Missing secret_key_base for 'production' environment, set this string with bin/rails credentials:edit #23 1.053 /rails/config/environment.rb:5:in `' #23 1.053 Tasks: TOP => environment #23 1.053 (See full trace by running task with --trace)

我的 Dockerfile 中卡住的那一行是

# Precompiling assets for production without requiring secret RAILS_MASTER_KEY
RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile

如果我运行EDITOR=emacs bin/rails credentials:edit,我可以看到在加密凭据文件中已经设置了secret_base_key
在我的production.rb文件中,这一行被注释掉了:
  # config.require_master_key = true

如果我取消上面那一行的注释,错误会改变为:

 > [linux/arm64 build 10/10] RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile:
#22 0.999 Missing encryption key to decrypt file with. Ask your team for your master key and write it to /rails/config/master.key or put it in the ENV['RAILS_MASTER_KEY'].

但这两个已经是真实的了 - 在config/master.key中已经有一个文件(不在Git中),并且已经有一个RAILS_MASTER_KEY的环境变量。

此外,我的config/deploy.yml文件包含:

# Configure builder setup.
builder:
  args:
    RUBY_VERSION: "<%= Pathname.pwd.join('.ruby-version').read.strip.delete_prefix('ruby-') %>"
    BUNDLER_VERSION: "<%= Bundler::LockfileParser.new(Pathname.pwd.join('Gemfile.lock').read).bundler_version %>"
    RAILS_MASTER_KEY: "<%= ENV['RAILS_MASTER_KEY'] %>"
2个回答

6
Rails 7.1 中引入了 SECRET_KEY_BASE_DUMMY=1,这意味着您仍然需要提供真实的 RAILS_MASTER_KEY对于 Rails 7.0.x: 在 Dockerfile 中,在 precompile 行之前添加以下内容:
ARG RAILS_MASTER_KEY
ENV RAILS_MASTER_KEY=$RAILS_MASTER_KEY

然后您可以删除SECRET_KEY_BASE_DUMMY=1,只留下RUN ./bin/rails assets:precompile。这将根据运行容器时MRSK传递的参数创建ENV。

对于Rails 7.1

使用新引入的SECRET_KEY_BASE_DUMMY=1,告诉预编译步骤在预编译时绕过密钥基础。


1
当然,选项#1非常不安全,但是为了测试/学习目的可以作为一个选项。 - Gorka
1
如果您仍需要在Docker的构建时使用secrets,应该使用带有MRSK的docker secrets。这里有描述 https://github.com/mrsked/mrsk#using-build-secrets-for-new-images顺便说一句,在构建时使用RAILS_MASTER_KEY不是一个好主意。 - Pavel Kalashnikov
2
在Rails 7.0中,我们能够简单地使用RUN SECRET_KEY_BASE=DUMMY ./bin/rails assets:precompile而无需注入主密钥以供在docker构建中使用。 - Michael
我已经卡在这个问题上好几天了。我不确定我做错了什么。我甚至尝试了重新安装Rails,但仍然遇到相同的错误。 - undefined
你使用的是哪个Rails版本? 你能把错误信息和Dockerfile粘贴在这里吗? - undefined
显示剩余5条评论

-1

您需要在部署的服务器上添加master.key文件,或将密钥添加到ENV ['RAILS_MASTER_KEY']中。 根据我在mrsk readme.md中所读到的内容,它使用.env文件,因此您需要在您的.env文件中添加RAILS_MASTER_KEY:'your_master.key'


它已经在 .env 中了 - Jason FB
1
正如@gorka在被接受的答案中所解释的那样,问题在于Docker环境中的env设置不作为构建器参数可用。由于预编译发生在Docker中(而不是运行应用程序),因此在运行应用程序时密钥的存在或不存在与阻止器无关。我的主要关注点是不做任何不安全的事情,将Rails主密钥提交到git是不安全的。 - Jason FB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接