Jenkins发布流水线Github认证失败,求无需SSH的解决办法
问题描述
我配置了一个用于发布的Jenkins多分支流水线任务,通过Jenkins Github插件拉取项目并构建。
简化后的DSL配置如下:
multibranchPipelineJob('Release') { ... branchSources { branchSource { source { github { id('AAA') repoOwner('BBB') repository('CCC') credentialsId('github-credentials') repositoryUrl('https://github.com/BBB/CCC') configuredByUrl(false) } } ... } } ... }
简化后的Jenkinsfile如下:
pipeline { agent any stages { stage('Build & Release') { steps { sh "./gradlew clean build release" } } } }
执行release任务时出现如下异常:
Caused by: org.eclipse.jgit.errors.TransportException: https://github.com/BBB/CCC.git: Authentication is required but no CredentialsProvider has been registered at org.eclipse.jgit.transport.TransportHttp.connect(TransportHttp.java:531) at org.eclipse.jgit.transport.TransportHttp.openPush(TransportHttp.java:434) at org.eclipse.jgit.transport.PushProcess.execute(PushProcess.java:127) at org.eclipse.jgit.transport.Transport.push(Transport.java:1335) at org.eclipse.jgit.api.PushCommand.call(PushCommand.java:137)
我认为release任务尝试连接Github进行推送,但我们不想为Jenkins在Github维护独立用户,也未配置SSH密钥。请问如何无需配置Github SSH密钥解决该问题?
解决方案
方法1:复用Jenkins已配置的HTTPS凭证
- 利用Jenkins中已有的
github-credentials(需是具备仓库推送权限的Github个人访问令牌PAT),在流水线中临时修改git remote地址为带凭证的HTTPS链接,让Gradle推送时自动使用该凭证:
修改Jenkinsfile如下:pipeline { agent any stages { stage('Build & Release') { steps { withCredentials([usernamePassword(credentialsId: 'github-credentials', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) { sh "git remote set-url origin https://${GIT_USER}:${GIT_PASS}@github.com/BBB/CCC.git" sh "./gradlew clean build release" } } } } } - 确认
github-credentials的PAT权限:必须勾选repo权限,组织仓库还需确保PAT拥有对应组织的访问权限。
方法2:让Gradle直接读取Jenkins注入的凭证
- 在项目的
build.gradle中配置release插件的git地址,通过环境变量获取凭证:plugins { id 'release' } release { git { uri = "https://${System.getenv('GIT_USER')}:${System.getenv('GIT_PASS')}@github.com/BBB/CCC.git" } } - 然后在Jenkinsfile中通过
withCredentials注入凭证环境变量:
这种方式无需修改git remote,直接让Gradle使用凭证完成推送。pipeline { agent any stages { stage('Build & Release') { steps { withCredentials([usernamePassword(credentialsId: 'github-credentials', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PASS')]) { sh "./gradlew clean build release" } } } } }
注意事项
- 绝对不要将凭证硬编码到代码或配置文件中,始终通过Jenkins凭证管理系统注入。
- 优先使用Github个人访问令牌(PAT)而非账号密码,安全性更高,且可按需分配权限,记得定期轮换PAT。
内容的提问来源于stack exchange,提问作者Rishabh
相关产品推荐
相关产品推荐

