By Petr Kout, August 24, 2014
I use ssh-agent to store my ssh key so that I don’t have to enter the key passphrase every time I access one of my servers over ssh. When I run commands using my regular user (non-root), ssh-agent works as expected, stores the key and issuing commands accessing the server(s) doesn’t request the passphrase. However, when I run commands as a root user via sudo, the key forwarding is lost because its mechanism relies on the SSH_AUTH_SOCK environment variable. However, environment variables are removed when the user is switched to root via sudo. How do we prevent the SSH_AUTH_SOCK variable from being removed when issuing sudo, thereby passing on key forwarding to the root user?
Fortunately, there is a way to solve this problem. Sudo has a configuration option that allows to keep given environmental variables from the user issuing the sudo command. The options is called env_keep and can be configured by changing the settings in /etc/sudoers files as follows (always use visudo to edit the file):
visudo Defaults env_reset Defaults>root env_keep+=SSH_AUTH_SOCK
In other words, add the line keeping the SSH_AUTH_SOCK variable below the Defaults env_reset line. Then save the file and run
ssh-agent bash ssh-add
and you should be able to execute a sudo command that accesses your server using the non-sudo user’s key without being asked for the key passphrase.