Configuration in the environment with dotenv
24 January 2014
Security’s one of the most easily overlooked risks when developing software. The Rails community has recently had another dispute about the best way of storing access credentials to 3rd party services. According to the 12Factor app manifesto, configuration should be stored in the environment. This is where the dotenv
gem becomes useful.
dotenv
is a Ruby gem that lets you configure environment variables in a dotfile in the root of your project rather than setting them in your shell. It’s pretty useful and has made life a heck of a lot easier.
Here’s how to install dotenv and configure it to hold a Rails app’s secret token:
Include it as the first gem in your Gemfile. It must come before other gems that might use environment variables.
gem 'dotenv-rails', group: [:development, :test]
Then modify your config/initializers/secret_token.rb
to set the token from an environment variable:
Your::Application.config.secret_key_base = ENV["SECRET_TOKEN"]
And finally, create a .env
file in your project’s root:
SECRET_TOKEN=thisismydevelopmentsecret
When running in the development or test environments, those environment variables will be read from the .env
file. When you run in production, just set the secret as part of the environment configuration and it will be read as normal. As an alternative, those settings can be stored in a shared .env
file that’s symlinked as part of a Capistrano deploy. All of this is documented on the dotenv Github page.