简体   繁体   English

如何将 git/ssh 凭据传递给从 Jenkins 运行的 docker 映像?

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

I have a pretty basic Jenkinsfile:我有一个非常基本的 Jenkinsfile:

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

This is a Pipeline script run in a Groovy sandbox.这是在 Groovy 沙箱中运行的管道脚本。 my-command will run git clone , and MY_IMAGE contains ~/.ssh/id_rsa . my-command将运行git clone ,并且MY_IMAGE包含~/.ssh/id_rsa

This works at the moment but including id_rsa in the image is bad security practice.这目前有效,但在图像中包含id_rsa是不好的安全做法。

It would be better if the ssh keys (or other authentication credentials) lived in the Jenkins configuration.如果 ssh 密钥(或其他身份验证凭据)存在于 Jenkins 配置中会更好。 (It would also be ideal if known_hosts was in the Jenkins configuration, but that's a lower priority.) (如果 known_hosts 在 Jenkins 配置中也是理想的,但这是一个较低的优先级。)

I have Jenkins 2.150.1, what's the right way to set this up?我有 Jenkins 2.150.1,设置它的正确方法是什么?

If you store your SSH keys as a Jenkins credential , something like this should work:如果您将 SSH 密钥存储为Jenkins credential ,这样的事情应该可以工作:

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. withCredentials(...)管道步骤将获取 SSH 密钥并将其存储在您的作业可访问的临时目录中(通常是/var/lib/jenkins/workspace/<job path>@tmp 。)此目录将自动挂载在您的容器中作为一个卷,在同一路径下。

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.由于KEY_FILE_PATH环境变量也将传递给您的图像,因此您可以随意引用它,就像在上面的示例中将其复制到~/.ssh/id_rsa一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM