How to use git / GitHub with Capistrano

Martyn Loughran

This post was originally published on the New Bamboo blog, before New Bamboo joined thoughtbot in London.


I’m assuming that you’re using private key authentication for git and that you’ve got an ssh agent set up (if you’re running Leopard then you automatically have this).

The trick is to use ssh agent forwarding, now supported in Capistrano. It allows the server to pull the latest code from GitHub using your local private key and ssh agent. To understand how this trickery works take a look at this illustrated guide.

set :ssh_options, { :forward_agent => true }

One of the great things about git is that it’s really fast, even if you’re cloning an entire repository. However you can go even faster by using the repository_cache option in Capistrano. This essentially keeps a clone of your app on the server and then just does a git pull to fetch new changes and copies the directory across when you deploy.

set :repository_cache, "git_cache"
set :deploy_via, :remote_cache

Another recommended strategy is to specify a git branch. Otherwise you’ll default to deploying HEAD which might be some crazy experiment.

set :branch, "stable"

In case you haven’t used remote branches they’re really easy. Say you have a local stable branch. Push this to GitHub using:

git push GitHub stable

So the complete Capistrano file should look something like:

set :application, "your cool app"

# Source code
set :scm, :git
set :repository, "git@github.com:githubusername/gitrepo.git"
set :branch, "stable"
set :repository_cache, "git_cache"
set :deploy_via, :remote_cache
set :ssh_options, { :forward_agent => true }

# Deployment servers
role :app, "your server"
role :web, "your server"
role :db,  "your server", :primary => true
set :deploy_to, "/var/www/#{application}"