How to correctly authenticate git user with SSH key

I want to pull code from Bitbucket.org

`

  • copy: src=path/to/mykey.pub dest=/home/{{ username }}/.ssh/mykey.pub
    sudo: false

  • copy: src=path/to/mykey dest=/home/{{ username }}/.ssh/mykey mode=0600
    sudo: false

  • copy: src=path/to/known_hosts dest=/home/{{ username }}/.ssh/known_hosts
    sudo: false

  • authorized_key: user={{ username }} key=“{{ lookup(‘file’, ‘/home/{{username}}/.ssh/mykey.pub’) }}”

  • git: repo={{ project_repo }} dest={{ project_code }} version={{ branch }} accept_hostkey=true key_file=“{{ lookup(‘file’, ‘/home/{{ username }}/.ssh/mykey.pub’) }}”

`

After running this playbook I get:

`

“cmd”: “/usr/bin/git ls-remote git@bitbucket.org:/myusername/mypro.git -h refs/heads/develop”, “failed”: true

stderr: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

`

NOTICE: While using bash, I can execute the “cmd” command without errors (even without sudo). My user logs in and connect to the repo. I do not understand why ansible is not able to repeat it.

Couple of things to check:

Hope it helps.