使用Groovy创建基于GitHub Jenkinsfile的任务时如何传入GitSCM凭证
问题解决方案
你当前代码仅完成了全局SSH凭证的创建,但是在实例化GitSCM时没有关联对应凭证ID,Jenkins拉取GitHub代码时找不到认证信息,因此触发公钥权限报错。
修正后的完整代码
#!groovy import hudson.* import jenkins.* import jenkins.model.* import hudson.model.* import hudson.plugins.git.*; import com.cloudbees.plugins.credentials.impl.* import com.cloudbees.plugins.credentials.* import com.cloudbees.plugins.credentials.domains.* import com.cloudbees.jenkins.plugins.sshcredentials.impl.* // 创建访问GitHub的凭证 def parent = Jenkins.instance def source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource("HIDDEN") // 第二个参数为凭证ID,此处设置为GitHub def ck1 = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "GitHub", "user", source, "password", "My Description") SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ck1) // 创建流水线 - 核心修改部分 // 构造远程仓库配置,第四个参数传入之前创建的凭证ID def remoteConfig = new UserRemoteConfig("ssh-url", "origin", null, "GitHub") // 用带远程配置参数的构造方法实例化GitSCM def scm = new GitSCM([remoteConfig], [new BranchSpec("*/main")], false, [], null, null, []) def flowDefinition = new org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition(scm, "Jenkinsfile") def job = new org.jenkinsci.plugins.workflow.job.WorkflowJob(parent, "Dev-1") job.definition = flowDefinition parent.save() parent.reload()
关键修改点说明
- 构造
UserRemoteConfig实例时传入提前创建的凭证ID,需和BasicSSHUserPrivateKey初始化时的第二个参数完全一致,本案例中为GitHub,完成仓库地址和认证信息的绑定 - 替换原来仅传入仓库地址的简易
GitSCM构造方式,使用携带UserRemoteConfig列表参数的构造方法实例化SCM配置
额外校验项
- 确认填入
BasicSSHUserPrivateKey的私钥内容,和GitHub账号/仓库中配置的SSH公钥是配对关系 - 如果你的SSH私钥没有设置密码,创建凭证时的密码参数请传入空字符串
"",不要随意填写占位字符串 - 确认仓库SSH地址格式正确,标准格式为
git@github.com:<用户名>/<仓库名>.git - 确认对应GitHub账号对目标仓库拥有读取权限
内容的提问来源于stack exchange,提问作者Kaguei Nakueka
相关产品推荐
相关产品推荐

