如何正确地将 ssh 密钥文件从 Jenkins 凭证变量传递到 docker build 命令?

问题描述

这个问题是这个问题的后续 How to pass jenkins credentials into docker build command?

我从我的 groovy 管道中的 jenkins 凭证存储中获取 ssh 密钥文件,并且 通过 --build-arg 将它传递给 docker build 命令,以便我可以从我的 docker 容器内的私有 git 存储库中检出和构建工件

凭证存储 id :cicd-user,用于从我的常规 Jenkinsfile 中按预期检查我的私人作品

checkout([$class: 'GitSCM',userRemoteConfigs: [[credentialsId: 'cicd-user',url:'ssh://git@bitbucket.myorg.co:7999/A/software.git']]

我访问它并尝试将其传递给 docker build 命令:

  withCredentials([sshUserPrivateKey(credentialsId: 'cicd-user',keyFileVariable: 'FILE')]) { 
           sh "cd ${WORKSPACE} && docker build -t ${some-name} --build-arg USERNAME=cicd-user --build-arg  PRIV_KEY_FILE=\$FILE --network=host -f software/tools/jenkins/${some-name}/Dockerfile ."
        }

在 Dockerfile 中我做

RUN echo "$PRIV_KEY_FILE" > /home/"$USERNAME"/.ssh/id_rsa && \
 chmod 700 /home/"$USERNAME"/.ssh/id_rsa 

RUN echo "Host bitbucket.myorg.co\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config

但我看到以下问题

"加载密钥"/home/cicd-user/.ssh/id_rsa" :(格式无效) “git@Bitbucket.mycomp.co:权限被拒绝(公钥) “致命:无法从远程存储库读取”

过去我通过像下面这样的cat'ing从外部将ssh私钥作为--build-arg传递

--build-arg ssh_prv_key="$(cat ~/.ssh/id_rsa)"

我应该做类似的事情吗

--build-arg PRIV_KEY_FILE="$(cat $FILE)"

知道什么地方可能出错或我应该在哪里正确调试吗?

解决方法

我昨天遇到了同样的问题,我想我想出了一个可行的解决方案。

以下是我采取的基本步骤 - 使用 sshagent plugin 在 Jenkins 作业中管理 sshagent。您可能也可以使用 withCredentials,尽管我最终发现这不是成功的方法。

可以使用 docker build 命令 --ssh 标志使 ssagent(或密钥)可用于特定构建步骤。 (Feature reference) 需要注意的是,要使其正常工作(在当前时间),您需要设置 DOCKER_BUILDKIT=1。如果您忘记这样做,那么它似乎忽略了此配置并且 ssh 连接将失败。一旦设置,sshagent

减少看管道:

pipeline {
    agent {
        // ...
    }
    environment {
        // Necessary to enable Docker buildkit features such as --ssh
        DOCKER_BUILDKIT = "1"
    }
    stages {
        // other stages

        stage('Docker Build') {
            steps {
                // Start ssh agent and add the private key(s) that will be needed in docker build
                sshagent(['credentials-id-of-private-key']) {
                    // Make the default ssh agent (the one configured above) accessible in the build
                    sh 'docker build --ssh default .'
                }
            }
        // other stages
        }
    }
}

在 Dockerfile 中,有必要明确提供需要它访问 ssh 代理的行。这可以通过在相关的 RUN 命令中包含 mount=type=ssh 来完成。

对我来说,这大概是这样的:

FROM node:14
# Retrieve bitbucket host key
RUN mkdir -p -m -0600 ~/.ssh && ssh-keyscan bitbucket.org >> ~/.ssh/known_hosts
...
# Mount ssh agent for install
RUN --mount=type=ssh npm i
...

通过此配置,npm install 能够通过 sshagent 在 docker build 中使用 SSH 私钥来安装存储在 Bitbucket 上的私有 git 存储库。