SSH, Private Repos, Ansible and Vagrant

Lets say you want to setup a server using Vagrant and Ansible and you want to put your code onto the server by checking it out from a private repo from some place like BitBucket. Further, you want to make it possible for the server to checkout new updates. Here is one way to do it.

First create a RSA keypair. There are lots of examples of how to do it. This is a good one. When you complete this, you will have the keypair on your local machine, which will be useful if you want to check code from the repo.

Next, put a copy of your public key (*.pub) on the repo site (e.g. Bitbucket). The repo site will have instructions for how to do this.

After that, create an Ansible YMAL file and put both the private and public keys in it. Something like this:

git_repo: ssh://

- name: Create the Bitbucket SSH public key file
  copy: src="/path/to/your/local/public/key"

- name: Create the Bitbucket SSH private key file
  copy: src="/path/to/your/local/private/key"

- name: Setup the Git repo git: repo={{ git_repo }} dest={{ project_path }} accept_hostkey=yes when: setup_git_repo tags: git

When you run vagrant up or vagrant provision, you might get this error:

Permission denied (publickey).
 fatal: The remote end hung up unexpectedly

However, if you run vagrant ssh and manually git the repo, everything works. The reason for this is, in my case, Ansible was becoming root before pulling the code from the repo and root does not have the private key. Luckily, you can tell Ansible git which file to use, by using the key_file keyword. Like this:

- name: Setup the Git repo
  git: repo={{ git_repo }} dest={{ project_path }} accept_hostkey=yes key_file=/home/vagrant/.ssh/id_rsa_bitbucket
  when: setup_git_repo
  tags: git