来自 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')]){ 

知道我做错了什么吗?

withCredentials()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

上面对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 的解决方法

最新更新