Access private GitHub repos in Vagrant up

Vagrant has the feature to use SSH agent forwarding. This can be used to access other SSH hosts without a password and without inserting SSH keys into your Vagrant box.

Enable SSH agent forwarding

It is very easys to use SSH agent forwarding in interactive sessions while running vagrant ssh. The config setting in your Vagrantfile is this line

  config.ssh.forward_agent = true

Know your hosts

To make SSH agent forwarding work at provisioning time we have to do an additional step. The host where we want to SSH into has to be added to the known hosts in the Vagrant box.

For a concrete example we want to try to clone a private repo from GitHub. So we have to add the host github.com to the known_hosts file.

The following command can be added into a shell provision script.

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

After that a git clone can access GitHub via SSH with your SSH agent running on your host machine.

Complete example

Here is a complete Vagrantfile that can be used to test it.

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box = "boxcutter/ubuntu1404"
  config.ssh.forward_agent = true

  config.vm.provision "shell", inline: <<-SHELL
    sudo apt-get update
    sudo apt-get install -y git
    mkdir -p ~/.ssh
    chmod 700 ~/.ssh
    ssh-keyscan -H github.com >> ~/.ssh/known_hosts
    ssh -T git@github.com
    git clone git@github.com:you/your-private-repo
  SHELL
end

There may be issues on a Windows host even with an SSH agent running. Tested on a Mac.

Stefan Scherer

Read more posts by this author.