How to pass git/ssh credentials to a docker image run from Jenkins?

Viewed 367

I have a pretty basic Jenkinsfile:

docker.image('MY_IMAGE').inside {
  sh '/bin/my-command my-args'
}

This is a Pipeline script run in a Groovy sandbox. my-command will run git clone, and MY_IMAGE contains ~/.ssh/id_rsa.

This works at the moment but including id_rsa in the image is bad security practice.

It would be better if the ssh keys (or other authentication credentials) lived in the Jenkins configuration. (It would also be ideal if known_hosts was in the Jenkins configuration, but that's a lower priority.)

I have Jenkins 2.150.1, what's the right way to set this up?

1 Answers

If you store your SSH keys as a Jenkins credential, something like this should work:

withCredentials([sshUserPrivateKey(credentialsId: '<credential ID here>', keyFileVariable: 'KEY_FILE_PATH')]) {
    docker.image('MY_IMAGE').inside {
        sh 'cp $KEY_FILE_PATH ~/.ssh/id_rsa'
        sh '/bin/my-command my-args'
    }
}

The withCredentials(...) pipeline step will fetch the SSH key and store it in a temporary directory accessible to your job (usually /var/lib/jenkins/workspace/<job path>@tmp.) This directory will be automatically mounted in your container as a volume, under the same path.

Since the KEY_FILE_PATH environment variable will also be passed to your image, it can be referenced however you like, like copying it to ~/.ssh/id_rsa in the above example.

Related