Clone a private git repository with Ansible (using password prompt)

Written by - 5 comments

Published on - Listed in Linux Ansible Git

I'm currently setting up an automated application installation with Ansible. However parts of the installation require to clone/pull code from a private git repository.

A possibility would be to use private key authentication, however we all know that (as of this writing in December 2015) it is not possible to use the same public key on multiple git repositories in github.

So I found a way to let Ansible clone the repository with my own user, yet without hard-coding it of course.

At the begin of the playbook yaml, I ask for the credentials:

- name: ANSIBLE - Shop Installation
  hosts: '{{ target }}'

    - name: "githubuser"
      prompt: "Enter your github username"
      private: no
    - name: "githubpassword"
      prompt: "Enter your github password"
      private: yes


Later on in the task where the git repository should be cloned, I reference the now existing variables githubuser and githubpassword:

  - name: Get updated files from git repository
    git: repo=https://{{ githubuser }}:{{ githubpassword }} dest=/tmp/github

When running the playbook, the prompt  request arrives and then the repository is successfully cloned:

$ ansible-playbook playbooks/shop/repotest.yaml --extra-vars " env=test"
Enter your github username: Napsty
Enter your github password:

PLAY [ANSIBLE - Shop Installation] ***********************************************
TASK: [Get updated files from git repository] *******************************
changed: []

Success can be verified on the server: ls /tmp/github/  shop

Add a comment

Show form to leave a comment

Comments (newest first)

Austin Weisgrrau from wrote on Nov 30th, 2020:

Better use {{ githubcred | urlencode }} in case of special characters in the username or password

Nico Kadel-Garcia from US wrote on Jul 10th, 2018:

It's also possible to manipulate the ssh_opts setting to use a different deploy key for a specific git repository, and avoid the key conflicts

ck from Switzerland wrote on Jan 16th, 2018:

That's a good point, marcolussetti. In my case I actually used Bitbucket as repository source and there are no files left which would show the password. I didn't try it with a Github repo (although in the example above I used the address for my repo).
If a file contains the git password, it could be immediately removed right after the Ansible git task, as you suggest.

marcolussetti from wrote on Jan 15th, 2018:

This is cool, but it does save the user's password in the git remote. So one should probably consider either removing the git remote at the end of this or use SSH key forwarding instead.

Viktoria from wrote on Jun 16th, 2016:

Thank you very much, your idea is really helpful!