使用多分支管道 Jenkinsfile 时构建环境中的 SSH 密钥

Sam*_*way 2 python ssh pip jenkins

我有一个项目正在使用多分支管道插件在 Jenkins 上构建。我正在使用声明性管道语法,我的 Jenkinsfile 看起来像这样:

pipeline {
    agent { label 'blah' }
    options {
        timeout(time: 2, unit: 'HOURS')
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }
    triggers { pollSCM('H/5 * * * *') }
    stages {
        stage('Prepare') {
            steps {
                sh '''
                  echo "Building environment"
                  python3 -m venv venv && \
                  pip install git+ssh://git@my_private_repo.git
                '''
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当构建在 Jenkins 盒子上运行时,构建失败,当我检查控制台输出时,pip install 命令失败并出现错误:

Permission denied (publickey).
fatal: Could not read from remote repository.
Run Code Online (Sandbox Code Playgroud)

我猜测我需要将所需的 ssh 密钥设置到 jenkins 构建环境中,但我不确定如何执行此操作。

Jos*_*lta 5

您需要安装SSH 代理插件并使用它来将操作包装在steps指令中,以便能够从私有存储库中提取。您可以使用指令启用 SSH 代理sshagent,您需要传入一个参数,表示具有 git 存储库读取权限的有效密钥的哈希值。该密钥需要在 Jenkins 的全局凭证视图中可用(Jenkins -> Credentials [在左侧菜单上],搜索右侧密钥的 ID 字段),例如:

    stage('Prepare') {
        steps {
            sshagent(['<hash_for_your_key>']) {
                echo "Building environment"
                sh "python3.5 -m venv venv"
                sh "venv/bin/python3.5 venv/bin/pip install git+ssh://git@my_private_repo.git
            }
        }
Run Code Online (Sandbox Code Playgroud)

注意:由于指令下的操作steps作为子进程执行,因此您需要使用长语法从虚拟环境中显式调用可执行文件。