Skip to content

Instantly share code, notes, and snippets.

@raghubetina
Last active April 23, 2021 00:48
Show Gist options
  • Save raghubetina/0ab2baa497e1a97cdc3cde947c426251 to your computer and use it in GitHub Desktop.
Save raghubetina/0ab2baa497e1a97cdc3cde947c426251 to your computer and use it in GitHub Desktop.
Hiding your credentials from GitHub

Hiding your credentials from GitHub

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.

Install the gem

# Gemfile

gem "figaro"
bundle install
bundle exec figaro install

Add your secrets

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"

Use your secrets

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.

Setting Heroku environment variables

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment