Ansible and Git Permission denied (publickey) at Git Clone

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 in ~/.ssh/conf (I updated my question with the ansible.cfg that I had before fixing the issue).

The solution was to add transport = ssh to ansible.cfg under [defaults] plus running ansible-playbook from the location where ansible.cfg is located and make sure that the following setting exists in the /etc/ssh/sshd_config of the target box:

AllowAgentForwarding yes

My ansible.cfg now looks like this:

[defaults]
transport = ssh

[ssh_connection]
ssh_args = -o ForwardAgent=yes

To clone the private github repo over the remote server, I am doing this:

First add the ssh key to your ssh-agent:

eval `ssh-agent -s`
ssh-add ~/.ssh/my-private-key.pem

After that I have modified the ansible.cfg:

[defaults]
transport = ssh
sudo_flags = -HE

[ssh_connection]
ssh_args = -o ForwardAgent=yes

Now you can clone the github private repo even as root user

Normally, I also add these two tasks in my playbook/roles tasks as well:

- name: Tell the host about our servers it might want to ssh to
  known_hosts:
    path: '/etc/ssh/known_hosts'
    name: 'github.com'
    key: "{{ lookup('pipe', 'ssh-keyscan -t rsa bitbucket.org') }}"

- name: Upload sudo config for key forwarding as root
  lineinfile:
    dest: /etc/sudoers.d/ssh_key_forward
    line: 'Defaults env_keep+=SSH_AUTH_SOCK'
    create: yes
    owner: root 
    group: root 
    mode: "0440"
    state: present
    validate: 'visudo -c -f %s'

Strange, it work for me. If the ssh option didn't work for you then you can use the username/password option like this:

- name: Pull the code
  git:
    repo: "https://{{ bitbucket_login }}:{{ bitbucket_password|urlencode }}@bitbucket.org/path/project.git"
    dest: /var/www/myproject
    version: master

Hope that might helpful for you and others