如何让我的Rails应用程序使用我的〜/ .bashrc保存的ENV VARS?

时间:2015-02-09 22:29:55

标签: ruby-on-rails cmd environment-variables secret-key

我在〜/ .bashrc中保存了一些ENV,然后重新打开文件,我可以在那里看到它们:

export SECRET_KEY_BASE="secretkeyhere"
export S3_SECRET_KEY="anotherhere"
export S3_ACCESS_KEY="andhere"
export DEVISE_KEY="and again"

然而,当我告诉我的rails应用程序使用它们时,例如我的模型中使用ENV["S3_ACCESS_KEY"]的s3凭据,它似乎没有使用它们,给我错误:

Missing Credentials. Unable to find AWS credentials. You can configure your AWS credentials a few different ways: * Call AWS.config with :access_key_id and :secret_access_key * Export AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to ENV * On EC2 you can run instances with an IAM instance profile and credentials will be auto loaded from the instance metadata service on those instances. * Call AWS.config with :credential_provider. A credential provider should either include AWS::Core::CredentialProviders::Provider or respond to the same public methods. = Ruby on Rails In a Ruby on Rails application you may also specify your credentials in the following ways: * Via a config initializer script using any of the methods mentioned above (e.g. RAILS_ROOT/config/initializers/aws-sdk.rb). * Via a yaml configuration file located at RAILS_ROOT/config/aws.yml. This file should be formated like the default RAILS_ROOT/config/database.yml file.

在shell中我运行echo $DEVISE_KEY并且它只返回空行,如果我运行source ~/.bashrc然后echo $DEVISE_KEY它会返回密钥吗?!?所以它似乎在某处,但不能通过rails和/或正确的会话/环境/程序访问。作为UNIX的一名大三学生,Rails以及更多我现在对这里发生的事情感到茫然。请你帮我理解我在这里做错了什么。三江源。

1 个答案:

答案 0 :(得分:0)

作为在您的应用程序中处理环境变量的替代方法,我建议您查看dotenv gem

您不必处理〜/ .bashrc文件(在您的情况下肯定没有正确加载),您可以在本地环境中有一个.env文件,您可以在其中定义变量,这将是当环境被引导时加载到ENV中。您不会将.env文件提交到版本控制,并将其保留在您的环境本地。

在您的情况下,您会将变量添加到.env

SECRET_KEY_BASE="secretkeyhere"
S3_SECRET_KEY="anotherhere"
S3_ACCESS_KEY="andhere"
DEVISE_KEY="and again"

然后只需在您的AWS配置文件中调用它们,如下所示:

config.secret_key  = ENV['S3_SECRET_KEY'] 

(or whatever the config method is)

希望它有所帮助!