Sometimes you want to use a gem on Heroku that is in a private repository on GitHub.
Using git over http you can authenticate to GitHub using basic authentication. However, we don't want to embed usernames and passwords in Gemfiles. Instead, we can use authentication tokens.
- Get an OAuth Token from GitHub
First you will need to get an OAuth Token from GitHub using your own username and "note"
$ curl -u 'masonforest' -d '{"scopes":["repo"],"note":"Ventana Example App"}' https://api.github.com/authorizations
- Authenticate bundler to GitHub via OAuth Token
Add this line to your Gemfile replacing "your_token" with the token you got from step 1. In this example we are installing the 'ventana' gem:
gem 'ventana', git: "https://your_token:x-oauth-basic@github.com/thoughtbot/ventana.git"
For additional security you can store your OAuth token in an environment variable. This way your token is not included in your codebase which is insecure. However this technique relies on on a Heroku labs feature which can change/be revoked at any time.
Change the line in your Gemfile to
gem 'ventana', git: "https://#{ENV['GITHUB_TOKEN']}:x-oauth-basic@github.com/thoughtbot/ventana.git"
Then set the your access token locally using the token you got from above:
$ export GITHUB_TOKEN=your_token
Now bundle and if everything works locally you are ready to deploy to Heroku!
Environment variables such as GITHUB_TOKEN are not available at build time to Heroku by default.
To make them available, you will need to enable the "user-env-compile" feature
$ heroku labs:enable user-env-compile -a ventana-demo
Finally add the GITHUB_TOKEN to your Heroku environment
$ heroku config:add GITHUB_TOKEN=your_token
You now have a private gem installed on Heroku!
Awesome!
I tried using ENV variables in the past with a "deploy user" but it's much easier (and user specific) to create deploy tokens!
Sneaky hint for those on OS X, if you use .rvmrc files you can export the token in there meaning it can be app specific, or you can use .env and foreman...