Ssh – Permission denied (publickey) when cloning git repo, but SSH works fine

gitpublic-keyssh

I'm attempting to clone a git repo using SSH protocol like so:

sudo git clone ryan@example.com:/var/www/repo

But I'm getting the "Permission denied (publickey)" error. However, I already placed my public key in the authorized_keys file, and it works fine when I SSH into the same server using the same user like so:

ssh ryan@example.com

It also works fine if I clone the same repository to a different machine. The only difference between the way I set up the two machines is this: On the machine that doesn't work, I copied and pasted the public key into authorized_keys manually. On the machine that does work, I set it up using ssh-copy-id. Is git using some different authentication method than SSH, even though I'm using the SSH protocol? Why can I connect using SSH but can't use git via SSH?

UPDATE:

As suggested below, the issue was due to using sudo when cloning. This will then authenticate using the root user, and since I have disabled SSH access for root, it was blocked. I solved this by adding myself to the www-data group which owns the local directory, and then giving write permissions for the group.

Best Answer

When running commands with sudo they run as the target user (root in this case since that is the default user and you didn’t select a specific one with a -u username option) .

That means rather than your ssh keys, those belonging to root are used. Either configure git for the root user to use the key pair from your account or (generate and) use the root ssh key pair to get authorization to your git repo