roger
roger

Reputation: 9893

How to use dotenv to add Environment Variables to ruby on rails application?

I want to set SECRET_KEY_BASE which is used in secrets.yml:

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

I have tried to add code as follow in .profile:

export SECRET_KEY_BASE=cfbc3b45d65db30b853cdc0557e0be85609cf75974ebb706f46a00abe09eee9454b3d311e48ee4157e1e5d5e3de5b8d2a329dff13871837cbaeae6af2bc2e42f

it works well, but this is still not that better, I know that dotenv can add this in a .env file in root path of app, so I add

gem 'dotenv-rails'
gem 'dotenv-deployment'

then I add code as follow into .env.production in root path of rails app:

SECRET_KEY_BASE=cfbc3b45d65db30b853cdc0557e0be85609cf75974ebb706f46a00abe09eee9454b3d311e48ee4157e1e5d5e3de5b8d2a329dff13871837cbaeae6af2bc2e42f

But why this doesn't work?

Upvotes: 2

Views: 1505

Answers (1)

user3724235
user3724235

Reputation: 33

In Rails 4.1, config/secrets.yml is the new default location for secret_key_base of your application. It can, however, be used also for storing other secret variables, making it a good place for environment-specific tokens, API keys etc.

Fill the file with the secrets you want to store, for example:

development:
  secret_key_base: your_development_secret
  api_key: some_key
production:
  secret_key_base: your_production_secret
  twitter_consumer_key: production_twitter_key
  twitter_consumer_secret: production_twitter_secret
  twitter_oauth_token: production_oauth_token
  twitter_oauth_token_secret: production_oauth_secret

In your code, you can access these secrets with Rails.application.secrets:

Twitter.configure do |config|
  config.consumer_key       = Rails.application.secrets.twitter_consumer_key
  config.consumer_secret    = Rails.application.secrets.twitter_consumer_secret
  config.oauth_token        = Rails.application.secrets.twitter_oauth_token
  config.oauth_token_secret = Rails.application.secrets.twitter_oauth_token_secret
end

The secrets.yml will be checked into git by default, add it to your .gitignore file.

Upvotes: 2

Related Questions