Capistrano has the option to forward the local SSH agent to the remote server it wants to deploy on. But for this to work a SSH agent must be running and the key(s) you want to forward must be added to that SSH agent.
First I tried to start the SSH agent with the Capistrano deploy.rb recipe, but I could not get that to work and also the killing of the SSH agent afterwards could be a problem.
Eventually I solved it by adding the following line to the crontab of the deploy user. This line will be executed on server (re)boot by the deploy user. The agent won’t have to be started and killed every time and will just keep running until the next reboot. After the reboot the SSH agent will be automatically started again with the cronjob.
@reboot sh -c 'eval `ssh-agent -a /var/lib/jenkins/.ssh/ssh-agent.sock`; ssh-add /var/lib/jenkins/.ssh/id_rsa'
The SSH part of your Capistrano recipe must look like:
set :ssh_options, { :forward_agent => true } ENV['SSH_AUTH_SOCK'] = '/var/lib/jenkins/.ssh/ssh-agent.sock'
For showing SSH debug information add the following line. This information can be very useful!
ssh_options[:verbose] = :debug