---
title: How to use git / GitHub with Capistrano
teaser: 'Use git inside your capistrano scripts to speed up deployment.

  '
tags: git,devtools,new bamboo,web
author: Martyn Loughran
published_on: 2008-03-12
---

_This post was originally published on the New Bamboo blog, before [New Bamboo
joined thoughtbot in London][new-bamboo-thoughtbot]._

---

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][ssh-forwarding].

```ruby
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.

```ruby
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.

```ruby
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:

```sh
git push GitHub stable
```

So the complete Capistrano file should look something like:

```ruby
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}"
```

[new-bamboo-thoughtbot]: https://thoughtbot.com/blog/new-bamboo-joins-thoughtbot-in-london
[ssh-forwarding]: http://www.unixwiz.net/techtips/ssh-agent-forwarding.html
