Antable and Git Permission denied (publickey) at Git Clone


I have a playbook where I am trying to clone from a private repo (GIT) to a server.

I have setup ssh forwarding and when I ssh into the server and try to manually clone from the same repo, it successfully works. However, when I use ansible for the to clone the repo to the server, it fails with "Permission Denied Public Key".

This is my playbook deploy.yml:


- hosts: webservers
  remote_user: root

      - name: Setup Git repo
        git: repo={{ git_repo }}
             dest={{ app_dir }}

This is how my ansible.cfg looks:

ssh_args = -o FowardAgent=yes

I am also able to perform all the other tasks in my playbooks (os operations, installations).

I have tried:

  • Specifying sshAgentForwarding flag in ansible.cfg on the server (ansible.cfg in same dir as playbook) using:

    ssh_args = -o ForwardingAgent=yes

  • used become: false to execute the git clone
  • running ansible -i devops/hosts webservers -a "ssh -T [email protected]" returns:

    an_ip_address | UNREACHABLE! => { "changed": false, "msg": "Failed to connect to the host via ssh.", "unreachable": true }

This is the command that I use to run the playbook: ansible-playbook devops/deploy.yml -i devops/hosts -vvvv This is the error message I get:

fatal: []: FAILED! => {"changed": false, "cmd": "/usr/bin/git ls-remote '' -h refs/heads/HEAD", "failed": true, "invocation": {"module_args": {"accept_hostkey": true, "bare": false, "clone":
 true, "depth": null, "dest": "/var/www/aWebsite", "executable": null, "force": false, "key_file": null, "recursive": true, "reference": null, "refspec": null, "remote": "origin", "repo": "[email protected]:aUser/aRepo.git", "ssh_opts": null, "track_submodules": false, "update": true, "verify_commit": false, "version": "HEAD"}, "module_name": "git"}, "msg": "Permission denied (publickey).\r\nfatal: Could not r$ad from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.", "rc": 128, "stderr": "Permission denied (publickey).\r\nfatal: Could not read from remote r$pository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n", "stdout": "", "stdout_lines": []}

By reading the documentation for ssh forwarding in ansible. I was able to figure out the solution.

The problem was that my ssh keys were not being forwarded because Ansible does not by default forward your keys, even if you have set up the key forwarding on ~/.ssh/conf (I updated my question with the ansible.cfg that I had before fixing the issue).

The solution is was to add transport = ssh to ansible.cfg under [defaults] plus running ansible-playbook from the location where ansible.cfg is located.

My ansible.cfg now looks like this:

transport = ssh

ssh_args = -o ForwardAgent=yes