Capistrano GitHub Authentication using Personal Access Tokens

Capistrano can deploy from various code hosting platforms. GitHub is one of the most popular hosting platforms and allows you to clone repos with SSH or HTTPS. This guide focuses on HTTPS. To deploy via HTTPS you’ll need a Personal Access Token, this guide explains how Personal Access Tokens are created and why they’re used in place of passwords.

Here’s the Capistrano code required to use GitHub over HTTPS:

1
2
3
set :repo_url, 'https://github.com/mintbit/example.git'
set :git_http_username, 'mintbit'
set :git_http_password, 'token123'

Removing hardcoded password

It goes without saying that hardcoding a Personal Access Token in the Capistrano deployment script is a bad idea. There are a few ways to fix it. One option is to use environment variables. Another option is to have Capistrano ask for the password on each deploy. Here’s how to do that:

1
2
3
4
set :repo_url, 'https://github.com/mintbit/example.git'
set :git_http_username, 'mintbit'
ask(:github_token, "github_token", echo: false)
set :git_http_password, fetch((:github_token))

If you’re deploying frequently, the password prompt will become annoying. However, it’s a nice solution for apps that are deployed infrequently because it reduces the complexity of project setup.