Jenkins管道中的Git使用错误的SSH私钥将其推回到Git存储库中

时间:2019-04-02 13:40:42

标签: git jenkins

我要拉出一个公共git仓库,并试图使用denpal(SSH私钥)凭据将我的更改推回到该仓库中。

stages {
  stage('Git clone') {
    steps {
      git branch: 'feature/Jenkinsfile',
        credentialsId: 'denpal',
        url: 'git@github.com:test/denpal.git'
    }
  }
  stage('Test Git') {
    steps {
      withCredentials([sshUserPrivateKey(credentialsId: 'denpal', keyFileVariable: 'SSH_KEY')]) {
        sh '''
        git commit --allow-empty -m "test withCredentials"
        git push origin feature/Jenkinsfile
        '''
      }
    }
  }

不幸的是,这给出了以下错误:

 > git --version # timeout=10
using GIT_SSH to set credentials denpal
 > git fetch --tags --force --progress git@github.com:test/denpal.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/feature/Jenkinsfile^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/feature/Jenkinsfile^{commit} # timeout=10
Checking out Revision ... (refs/remotes/origin/feature/Jenkinsfile)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f ...
 > git branch -a -v --no-abbrev # timeout=10
 > git branch -D feature/Jenkinsfile # timeout=10
 > git checkout -b feature/Jenkinsfile ...
Commit message: "empty"
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Test Git)
[Pipeline] withCredentials
Masking only exact matches of $SSH_KEY
[Pipeline] {
[Pipeline] sh
+ git commit --allow-empty -m test withCredentials
[feature/Jenkinsfile 3ff21fc] test withCredentials
+ git push origin feature/Jenkinsfile
ERROR: Permission to test/denpal.git denied to technology-labs.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
[Pipeline] }
[Pipeline] // withCredentials  

我也尝试过,但这也失败了:

withCredentials([sshUserPrivateKey(credentialsId: 'denpal', keyFileVariable: 'private_key', passphraseVariable: '', usernameVariable: 'git')]){ 

知道我在做什么错吗?

2 个答案:

答案 0 :(得分:0)

withCredentials()sshUserPrivateKey行将私钥写入一个临时文件并将位置分配给$SSH_KEY,但是由于没有引用{{1} }。

您可以使用$SSH_KEYdocs)向ssh和git告知私钥文件。

替换:

$GIT_SSH_COMMAND

具有:

git push origin feature/Jenkinsfile

答案 1 :(得分:0)

对上面 Rob 的回答的更全面的描述,让 git checkout 与 Jenkins 声明式管道语法的子模块一起工作。

#!/usr/bin/env groovy

pipeline {
    agent any
    stages {

        stage ('Clone') {
            steps {
                checkout scm
                withCredentials([sshUserPrivateKey(credentialsId: 'bitbucket_ssh', keyFileVariable: 'SSH_KEY')]) {
                    sh 'GIT_SSH_COMMAND="ssh -i $SSH_KEY" git submodule update --init'
                }
            }
        }
    ...
    }
}

这是 https://issues.jenkins.io/browse/JENKINS-20941

的解决方法