Managing Environment Variables in Rails

April 5, 2022   • rails

Don’t set the environment variables on the development machines, CI servers, or even production servers. Use the dotenv gem that lets you load variables from a .env file into the ENV hash when the Rails application loads.

Add this line to the top of your application’s Gemfile:

# A Ruby gem to load environment variables from `.env`.
gem 'dotenv-rails', groups: [:development, :test]

Then install the gem using Bundler:

$ bundle

Add your application configuration to your *.env* file at the root of your project:

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

Whenever your application loads, these variables will be available in ENV:

config.fog_directory  = ENV['S3_BUCKET']

Don’t forget to add the .env file to the .gitignore file so you don’t accidentally push it to Github for the whole world to see.