2

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?

spraff
  • 32,570
  • 22
  • 121
  • 229
  • how about `cat some_config > the id_rsa_file`? or, as a walkaround, use git token instead(as it can be readonly)? – Lei Yang Feb 07 '22 at 14:55
  • Where would the `cat` expression live? Where would `some_config` live? I'm unfamiliar with Jenkins – spraff Feb 07 '22 at 15:15
  • i'm not familiar with jenkins, either -_-. but some experience with gitlab ci. there must be some where to config the file content, and then jenkins can run shell command right? so `docker run --env from_someconfig dockername bash -c 'echo env_var' > id_rsa` ? – Lei Yang Feb 07 '22 at 15:19
  • Related: [Using SSH keys inside docker container](https://stackoverflow.com/q/18136389/16586783) – Arun Kumar B Feb 08 '22 at 10:49

1 Answers1

0

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.

Sam Weaver
  • 1,027
  • 16
  • 30