In many cases, we need to use secret information in our Ruby; most commonly, API keys and email account passwords.
You should never paste these strings directly into your Ruby code. There are bots that can and will steal your API keys the instant you push your code to a public GitHub repository. Even if you pay for private repositories, it's a good idea to not store secrets in your repo -- you may not want all of your collaborators (interns?) to know, for example, the API keys to your payment processor.
(If you have already pushed an API key to a public repository, you should sign into your API dashboard now and invalidate that old key, and get a new one. Assume that the old one has already been stolen. Reverting your commit will do no good.)
But if our Ruby needs to use these secrets, but we can't keep them in our code, what's the solution? Environment variables. We're going to use a gem called Figaro to make this easy.
# Gemfile
gem "figaro"
bundle install
bundle exec figaro install
The figaro install
command created a commented config/application.yml
file and adds it to your .gitignore
. Add your secrets to this file, e.g.,
# config/application.yml
mailgun_user_name: "[email protected]"
mailgun_password: "super-secret-password"
The values in this config/application.yml
can be accessed through the ENV
hash, e.g.,
# config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mailgun.org',
port: 587,
domain: 'your-domain.com',
user_name: ENV["mailgun_user_name"],
password: ENV["mailgun_password"],
authentication: 'plain',
enable_starttls_auto: true }
That's it! The config/application.yml
file will not be synced to GitHub, so your repo is now secure.
Deploying to Heroku? You can easily set your environment variables on your Heroku server, too:
figaro heroku:set -e production
See the Figaro gem docs for more info.