如何在jenkins管道中获取附加的远程git分支

如何在jenkins管道中获取附加的远程git分支,git,jenkins,jenkins-pipeline,Git,Jenkins,Jenkins Pipeline,我想在詹金斯做以下工作: 签出/克隆branch1中的my git repository 获取branch2(位于branch1之前) 获取branch1和branch2之间的所有提交用户 我正在使用管道 因此,我通过以下方式进行结账: git branch: 'branch1', credentialsId: 'XXX', url: 'XXX' 现在,我想另外获取'branch2',我尝试了: sh 'git fetch origin branch2:branch2' 但由于缺少凭据,这一

我想在詹金斯做以下工作:

  • 签出/克隆branch1中的my git repository
  • 获取branch2(位于branch1之前)
  • 获取branch1和branch2之间的所有提交用户
  • 我正在使用管道

    因此,我通过以下方式进行结账:

    git branch: 'branch1', credentialsId: 'XXX', url: 'XXX'
    
    现在,我想另外获取'branch2',我尝试了:

    sh 'git fetch origin branch2:branch2'
    
    但由于缺少凭据,这一点失败了


    那么如何做到这一点呢?

    您可以使用git credential helper和credentials插件。 Git凭证文档: 凭据插件:

    withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'git', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) {
        try {
            sh("git config credential.username ${env.GIT_USERNAME}")
            sh("git config credential.helper '!f() { echo password=\$GIT_PASSWORD; }; f'")
            sh("GIT_ASKPASS=true git fetch origin branch2:branch2")
        } catch (err) {
            println err
            error "ERROR: Failed to fetch changes"
        } finally {
            sh("git config --unset credential.username")
            sh("git config --unset credential.helper")
        }
    }