How to use the SSH Agent Plugin

Article ID:360029470091
2 minute readKnowledge base

Issue

  • I would like to use ssh based operations from within a build.

Resolution

This article details an example of usage The SSH Agent Plugin performing a Secure copy (scp) from an agent to another server.

NOTES:

  • Please read the requirements from the SSH Agents section in the SSH Credentials Management with Jenkins article

  • On recent versions of the plugin (greater than 1.14), this should work out of the box on Linux. However, it will require you to manually install ssh-agent on Windows.

  • This article does not cover the installation of ssh-agent, as the steps really depend on your setup and OS version.

The following steps should get you going:

Setup the credentials

Create a new credential of type SSH Username with private key:

add credentials
You can select the method of your choice to enter the Private Key. In case you have troubles creating credentials, please refer to Injecting Secrets into Jenkins Build Jobs.

Setup the Job (Pipeline)

You can simply use the sshagent step that will inject the credentials, as the following example:

sshagent(['my-ssh-key']) { sh 'scp /Users/exampleUser/home/aws/listDProcessesNativeStacks.sh ubuntu@ip-172-31-69-105.ec2.internal:/home/ubuntu' }

Setup the Job (Non Pipeline Jobs)

  1. In your freestyle job, tick the SSH Agent in the Build Environment section and select the credential you just created.

  2. In your Build section, you can now use scp, the SSH Agent step will properly inject the credential and you can simply run the scp command.

setup job

Troubleshooting

  • ERROR: Failed to run ssh-add tells that something was wrong with the ssh based operations. To dig into the issue, try to run manually the same operation (e.g: scp /Users/exampleUser/home/aws/listDProcessesNativeStacks.sh ubuntu@ip-172-31-69-105.ec2.internal:/home/ubuntu) from the agent which is running the build adding the private key to the ssh-agent manually (e.g. in linux ssh-add ~/.ssh/my-ssh-key).

Tested product/plugin versions

The latest update of this article has been tested with