ruby-on-railsruby-on-rails-4environment-variablesfigaro-ruby

Using Figaro and Secrets.yml to Manage Env Variables


I have a rails 4.1 app and I'm trying to organize my env variables. As of right now I have a secrets.yml file in my config/ folder. I also installed the figaro gem. My goal was to have all my env variables in the application.yml (not checked into git) file and then use the secrets.yml (checked into git) file to map the variables from appliation.yml to the application. When I print the files using Rails.application.secrets It just shows hashes that look like this:

:salesforce_username=>"ENV['SALESFORCE_USERNAME']"

None of my external services are working with this env variables setup. When I view the traces, the actually ENV['ACCOUNT_ID'] are being passed through in the requests like this:

v2/accounts/ENV['ACCOUNT_ID']/envelopes

In addition, I cannot access my env variables using Rails.application.secrets.account_id in my app.

secrets.yml

development:
  account_id: <%= ENV['ACCOUNT_ID'] %>

aplication.yml

development:
  ACCOUNT_ID: "123456"

application.rb

# preload tokens in application.yml to local ENV
config = YAML.load(File.read(File.expand_path('../application.yml', __FILE__)))
config.merge! config.fetch(Rails.env, {})
config.each do |key, value|
  ENV[key] = value.to_s unless value.kind_of? Hash
end

Solution

  • The gem provides a generator:

    $ rails generate figaro:install
    

    The generator creates a config/application.yml file and modifies the .gitignore file to prevent the file from being checked into a git repository.

    You can add environment variables as key/value pairs to config/application.yml:

    GMAIL_USERNAME: Your_Username
    

    The environment variables will be available anywhere in your application as ENV variables:

    ENV["GMAIL_USERNAME"]
    

    This gives you the convenience of using the same variables in code whether they are set by the Unix shell or the figaro gem’s config/application.yml. Variables in the config/application.yml file will override environment variables set in the Unix shell.

    In tests or other situations where ENV variables might not be appropriate, you can access the configuration values as Figaro method calls:

    Figaro.env.gmail_username
    

    Use this syntax for setting different credentials in development, test, or production environments:

    HELLO: world
    development:
      HELLO: developers
    production:
      HELLO: users
    

    In this case, ENV["HELLO"] will produce “developers” in development, “users” in production and “world” otherwise.