Easiest Way to Manage Heroku Environment Variables for Rack Apps

Recall that there have been some problems with YAML for configuration apart from vulnerability issues. I also grew sick of using it for configuration honestly. But then if you use Rails, you have to keep doing things “the Rails way” which is not necessarily “the sensible way.”

Storing configuration in the environment is one of the tenets of a twelve-factor app.

This convention is reasonable. Starting to get rid of YAML for configuration because there is a way to do so and probably be happy with that choice.

At an average, we have 2 to 4 environments (development, test, production and staging). Keeping 4 files rather than one big YAML file makes sense to me.

What can go wrong? If we forget to set environment variables for any environment including production, the app will not work.

There are many gems like figaro and dotenv. All work well but for Sinatra and Cuba apps, I use heroku config.

You would need to create at least 2 shell files that contain credentials and other info used by your application. One would be for development and another for production. Both files should be on your gitignore or global gitignore file.

Install heroku-config

$ heroku plugins:install git://github.com/ddollar/heroku-config.git
# config/production.env.sh
APP_HOST='yourapp.host'

To set the environment variables for Heroku, it would be this simple:

cat config/production.env.sh | heroku config:push

On a Cuba application, I don’t have any YAML files for configuration. But there’s this code taken from the Cuba app example:

module Settings
  File.read('env.sh').scan(/(.*?)='?(.*)'?$/).each do |key, value|
    ENV[key] ||= value
  end

  AUTHOR  = ENV['APP_AUTHOR']
  DESCRIPTION = ENV['APP_DESCRIPTION']
  HOST = ENV['APP_HOST']
  NAME = ENV['APP_NAME']
  SECRET_KEY = ENV['SECRET_KEY']
end

No YAML files. Good change!

This is not a sponsored post but since Packt asked me to mention about the campaign, please check PacktLib Plus to get 5 free downloads on your first month of subscription. The promotion ends on November 4.