Rails App中的生产环境变量

时间:2018-08-20 18:07:31

标签: ruby-on-rails ubuntu-18.04

我有一个Rails应用,我在控制器中包含一个api密钥。在控制器中,我有:

def email_signup
    email_address = params[:email_address]

    url = URI("https://api.sendgrid.com/v3/contactdb/recipients")

    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE

    request = Net::HTTP::Post.new(url)
    api_key = ENV['SENDGRID_API_KEY']
    request["authorization"] = "Bearer #{api_key}"
    request["content-type"] = 'application/json'
    request.body = [{"email": email_address}].to_json

    response = http.request(request)
    result = JSON.parse(response.body)
    Rails.logger.info "api_key is: #{api_key}"
    Rails.logger.info "Email response is: #{response.read_body}" #uncomment to view response/debug
    # redirect_to jobs_url, notice: result["errors"]

    redirect_to jobs_url, notice: "Thanks for Signing Up"
  end

在日志中,我看到:

I, [2018-08-17T19:54:17.439705 #24726]  INFO -- : [f0fce3e4-8574-49d4-84f9-a52c8e7cec24] api_key is:
I, [2018-08-17T19:54:17.439807 #24726]  INFO -- : [f0fce3e4-8574-49d4-84f9-a52c8e7cec24] Email response is: {"errors":[{"field":null,"message":"authorization required"}]}

因此,好像没有读取环境变量ENV['SENDGRID_API_KEY']。但是得到这个...如果我打开rails控制台并输入ENV['SENDGRID_API_KEY'],我会看到api键/字符串。

有什么想法为什么不起作用?

1 个答案:

答案 0 :(得分:0)

感谢Arup寻求解决方案。我采纳了他的建议,并通过在我的/etc/nginx/sites-enabled/default中添加以下内容来为乘客添加了环境变量:

passenger_env_var SENDGRID_API_KEY <my_key_here>;

...而且效果很好。很奇怪,因为即使我已将env变量添加到/ etc / environment并可以从控制台打印出env,但出于某种原因,Rails中的控制器仍未选择这些变量。