使用multibranch管道时,构建环境中的SSH密钥Jenkinsfile

时间:2017-06-12 10:11:12

标签: python jenkins ssh pip

我使用multibranch管道插件在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
                '''
            }
        }
    }
}

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

Permission denied (publickey).
fatal: Could not read from remote repository.

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

1 个答案:

答案 0 :(得分:3)

You need to install the SSH Agent plugin and use it to wrap the actions in the steps directive in order to be able to pull from a private repository. You enable the SSH Agent with the sshagent directive, where you need to pass in an argument representing the hash for a valid key with read permissions to the git repository. The key needs to be available in the global credentials view of Jenkins (Jenkins -> Credentials [on the left-hand side menu], search for the ID field of the right key), e.g.:

    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
            }
        }

N.B.: Because the actions under the steps directive are executed as subprocesses, you'll need to call explicitly the executable files from the virtual environment, using long syntax.

相关问题