What Is dotenv
dotenv sets environment variables from a .env file, to be accessed via ENV in Ruby. Using dotenv allows you to specify important global, environment-specifc configuration settings like API keys and secrets, usernames and passwords, and URIs in a file that’s not checked in to version control. These settings can then be accessed at run time using
Oh you mean like config/database.yml or config/environments/**.rb in Rails?
A lot like that. However, those files are generally checked in to version control software. It’s not a good idea to have important production passwords in your repo.
Why Should I Use dotenv
Fundamentally, configuration is not part of your application. It doesn’t belong in the same repo as the app itself. Putting it there can create numerous problems:
- Developers accidentally or naïvely committing changes that work for them but not others to a shared development-specific config file, breaking other developers’ dev environments
- Configuration containing sensitive passwords getting accidentally checked into version control, potentially leading to a security breach
- Creation of additional environments for QA, staging, etc. that are ‘just like production, except…’ leading to bloat and churn in config files
- Add .env to your .gitignore
- Add dotenv to your Gemfile:
gem 'dotenv-rails'if you’re using Rails or
- Create the file .env in the root directory of your project and specify variables inside, one per line, like so:
- If you’re using Rails, you should be able to access
ENV['MY_CONFIG_VAR'], but certain cases may require more tweaking, so see the readme if you have trouble
- If you’re using another framework or building a plain old Ruby app, add this somewhere that will be loaded before you need to access any variables:
require 'dotenv' Dotenv.load
- Set the same variables in a .env file for each environment (staging, production, etc.) and place these directly on each server (or with the code for configuring/provisioning servers)
- You’re done!
Strictly speaking, using dotenv in production is not recommended, so long term it may be worthwhile to find another way of setting the necessary environment variables. That said, many do use it in production without issue.
By way of example for step six, if you use Capistrano to deploy your app, the production .env file would live in the shared directory and be symlinked during deploy.