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://git@bitbucket.org/me/my_repo.git

- name: Create the Bitbucket SSH public key file
  copy: src="/path/to/your/local/public/key"
        dest=/home/vagrant/.ssh/id_rsa_bitbucket.pub
        mode=0644
        owner=vagrant
        group=vagrant

- name: Create the Bitbucket SSH private key file
  copy: src="/path/to/your/local/private/key"
        dest=/home/vagrant/.ssh/id_rsa_bitbucket
        mode=0600
        owner=vagrant
        group=vagrant

- 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
Advertisements

2 thoughts on “SSH, Private Repos, Ansible and Vagrant

  1. Thanks for the tips, but we can use like this:

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

    The sudo: False did the trick for it, where it will use the private key for the user that we have specified in the above step.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s