Sudo and ssh uses wrong key

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2022-05-26

If you call ssh (or a command that relies on it, like git clone) with sudo in front, it looks for the keys in a folder like /home/root/.ssh/id_rsa. But you probably never stored your key there - instead it will reside somewhere like /home/$USERNAME/.ssh/id_rsa

It fails with ssh-forwarding, too. This is because sudo removes all environment variables of your normal user, including $SSH_AUTH_SOCK, which is how SSH forwarding gets its magic. One way around, however, is to edit /etc/sudoers using visudo and set the env_keep variable

Defaults    env_keep+=SSH_AUTH_SOCK

An even easier way is to tell sudo to bring the environment with it for that command:

sudo -E ssh