How to expose a passphrase-authenticated SSH key stored in Jenkins to the Docker instance?

Article ID:218497418
1 minute readKnowledge base

Issue

Expose a passphrase-authenticated SSH key stored in Jenkins to the Docker instance

Environment

Resolution

This goal can be achieved with the SSH Agent plugin. Instead of writing the ssh key to a file, using this plugin allows you to expose a SSH agent. This agent will provide SSH keys stored in Jenkins. SSH client will connect to the agent and will be able to use the key to authenticate. Note that the private key is never written to the build agent, neither in the build container, the Agent plugin creates a special socket which lets SSH client communicates with Jenkins controller and authenticate with the private key.

Here is an example of using the SSH agent inside a docker pipeline build:

node {
  docker.image('cloudbees/java-build-tools:0.0.7.1').inside {
    sh 'id'
    sh 'ls -al ~/.ssh/ || true'
    sshagent(['credential-id']) {
       sh 'echo SSH_AUTH_SOCK=$SSH_AUTH_SOCK'
       sh 'ls -al $SSH_AUTH_SOCK || true'
       sh 'ssh -vvv -o StrictHostKeyChecking=no ubuntu@example.org uname -a'
    }
  }
}

If you are still unable to access the key, please refer to Why am I unable to authenticate via sshagent inside docker?