[英]Access to main app secrets from Rails engine initializer
I have been trying (unsuccessfully) to access the main app's application secrets from within my Rails mountable engine.我一直在尝试(未成功)从我的 Rails 可安装引擎中访问主应用程序的应用程序机密。 The whole point of a mountable engine is to provide modularity.
可安装引擎的全部意义在于提供模块化。 Therefore a common pattern would be to provide configurable parameters, some of which need to be secret, in the main app, which would then be used by the engine.
因此,一种常见的模式是在主应用程序中提供可配置的参数,其中一些需要保密,然后由引擎使用。
In my specific case, I am using carrierwave
and fog
in my engine to upload files to an AWS bucket.在我的具体案例中,我在引擎中使用
carrierwave
和fog
将文件上传到 AWS 存储桶。 The exact bucket and AWS credentials are not specified in the engine, but in the main app, since they will vary providing which app is mounting the engine.确切的存储桶和 AWS 凭据未在引擎中指定,但在主应用程序中指定,因为它们会因安装引擎的应用程序而异。
However, the initializer for carrierwave when mounted in the engine fails as it cannot find the Rails.application.secrets for the main app:但是,carrierwave 的初始化程序在安装在引擎中时会失败,因为它找不到主应用程序的 Rails.application.secrets:
require 'carrierwave'
require 'carrierwave/storage/fog'
CarrierWave.configure do |config|
config.fog_provider = 'fog/aws'
config.fog_credentials = {
:provider => 'AWS',
:aws_access_key_id => Rails.application.secrets.S3_AWS_ACCESS_KEY_ID,
:aws_secret_access_key => Rails.application.secrets.S3_AWS_SECRET_ACCESS_KEY
}
config.fog_directory = Rails.application.secrets.CARRIERWAVE_CONFIG_FOG_DIRECTORY
config.storage = :fog
end
This fails when engine is started with引擎启动时失败
Missing required arguments: aws_access_key_id, aws_secret_access_key (ArgumentError)
as in fact Rails.application.secrets.S3_AWS_ACCESS_KEY_ID
(and the others) evaluates to nil
in the initializer.事实上,
Rails.application.secrets.S3_AWS_ACCESS_KEY_ID
(和其他)在初始化程序中的计算结果为nil
。 It does evaluate correctly inside the engine's controllers once the app is running, but in the initializer it is nil.一旦应用程序运行,它确实在引擎的控制器内正确评估,但在初始化程序中它是零。
I have modified this like the following:我修改如下:
:aws_access_key_id => Rails.application.secrets.S3_AWS_ACCESS_KEY_ID || ENV["S3_AWS_ACCESS_KEY_ID"]
and exported the ENV VARIABLE in each production environment for use with the engine, but this is less than ideal.并在每个生产环境中导出 ENV VARIABLE 以供引擎使用,但这并不理想。 Any solution would be appreciated.
任何解决方案将不胜感激。
You should be able to have access to the secrets from initializer of your engine.您应该能够从引擎的初始化程序中访问秘密。
# path/to/your/engine/my_engine/lib/my_engine/engine.rb
module MyEngine
class Engine
initializer :my_custom_initializer do |app|
puts app.secrets
end
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.