Ansible: how to clone a repository as other user


I’m trying to write deployments rules with Ansible. Some of the steps are:

  1. Update and Upgrade Server
  2. Create a user called harry
  3. Add Public and Private keys to harry
  4. Clone a Git Repository from

I want to clone the repository as harry user in his home directory (that’s why I’m copying it’s public and private keys). The issue is that it is not possible to specifiy a user the git clone must be executed as. So Ansible try to clone the repository as root and failed because he doesn’t have rights to access the repository.

How do you solve this ?


As per Ansible’s documentation on Privilege Escalation, Ansible has limitations on becoming an unprivileged user as it exposes a security hole to Harry.

Using the Ansible git module, you can specify to use Harry’s private key from the privileged Ansible user using the key_file parameter, and using become_user allows the cloned files to be given ownership to Harry. For example:

Leave a Reply