首页 > 解决方案 > Jenkins 管道中的 Git 使用错误的 SSH 私钥推回 Git 存储库

问题描述

我正在提取一个公共 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')]){ 

知道我在做什么错吗?

标签: gitjenkins

解决方案


withCredentials()and行正在将sshUserPrivateKey私钥写入临时文件并将位置分配给$SSH_KEY,但它没有被使用,因为在那之后没有引用$SSH_KEY

$GIT_SSH_COMMAND您可以使用( docs )告诉 ssh 和 git 有关私钥文件的信息。

代替:

git push origin feature/Jenkinsfile

和:

GIT_SSH_COMMAND="ssh -i $SSH_KEY" git push origin feature/Jenkinsfile

推荐阅读