You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jenkins的init.groovy.d阶段用已有凭证通过Groovy克隆Git仓库?

实现方案

1. 编写Groovy初始化脚本(放置于Jenkins的init.groovy.d/目录下)

该脚本会在Jenkins启动阶段完成后执行,自动拉取Job DSL仓库并解析脚本,核心逻辑如下:

import jenkins.model.Jenkins
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials
import com.cloudbees.plugins.credentials.common.StandardSSHUserPrivateKeyCredentials
import javaposse.jobdsl.dsl.DslScriptLoader
import javaposse.jobdsl.plugin.JenkinsJobManagement
import java.net.URLEncoder

// 等待Jenkins完全初始化,确保JCasC加载的凭证已就绪
Jenkins.instance.waitUntilReady()

// 配置参数,请替换为你的实际信息
def repoUrl = "https://你的GHE域名/组织名/job-dsl仓库名.git"
def credId = "github-enterprise-creds" // JCasC创建的凭证ID
def targetDir = "/tmp/job-dsl-repo"
def jenkins = Jenkins.get()

// 根据ID查找已加载的凭证
def credentials = CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardCredentials.class,
    jenkins,
    null,
    null
).find { it.id == credId }

if (!credentials) {
    throw new Exception("未找到凭证ID ${credId},请检查JCasC配置是否正确加载")
}

// 构建带凭证的Git克隆命令
def gitCommand
if (credentials instanceof StandardUsernamePasswordCredentials) {
    // 处理用户名+密码类型凭证,生成带认证的仓库URL
    def encodedUser = URLEncoder.encode(credentials.username, "UTF-8")
    def encodedPass = URLEncoder.encode(credentials.password.plainText, "UTF-8")
    def authenticatedRepoUrl = repoUrl.replace("https://", "https://${encodedUser}:${encodedPass}@")
    gitCommand = "git clone ${authenticatedRepoUrl} ${targetDir}"
} else if (credentials instanceof StandardSSHUserPrivateKeyCredentials) {
    // 处理SSH密钥类型凭证,生成临时SSH配置
    def sshKeyFile = new File("/tmp/id_rsa_temp")
    sshKeyFile.text = credentials.privateKey
    sshKeyFile.setReadable(true, false)
    sshKeyFile.setWritable(true, false)
    
    def sshConfigFile = new File("/tmp/ssh_config_temp")
    sshConfigFile.text = """
        Host 你的GHE域名
            IdentityFile ${sshKeyFile.absolutePath}
            StrictHostKeyChecking no
    """.stripIndent()
    
    gitCommand = "GIT_SSH_COMMAND='ssh -F ${sshConfigFile.absolutePath}' git clone ${repoUrl} ${targetDir}"
} else {
    throw new Exception("不支持的凭证类型:${credentials.class.name}")
}

// 执行克隆命令
def proc = gitCommand.execute()
proc.waitFor()

if (proc.exitValue() != 0) {
    throw new Exception("仓库克隆失败:${proc.err.text}")
}

// 清理SSH类型凭证的临时文件
if (credentials instanceof StandardSSHUserPrivateKeyCredentials) {
    new File("/tmp/id_rsa_temp").delete()
    new File("/tmp/ssh_config_temp").delete()
}

// 解析并执行Job DSL脚本
def jobManagement = new JenkinsJobManagement(System.out, [:], new File(targetDir))
new DslScriptLoader(jobManagement).runScripts(
    new File(targetDir).listFiles().findAll { it.name.endsWith(".groovy") }
)

println "Job DSL脚本执行完成,已创建/更新相关任务"

2. 关键注意事项

  • 替换脚本中repoUrl、credId、你的GHE域名为实际信息
  • 确保Jenkins所在服务器/容器已安装git命令
  • SSH类型凭证的临时密钥文件会在克隆完成后自动删除,避免密钥泄露
  • 提前安装Job DSL插件、Git插件等依赖插件,确保脚本可正常解析
  • init.groovy.d目录下的脚本会随Jenkins启动自动执行,无需手动触发

内容的提问来源于stack exchange,提问作者Cory Ringdahl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:15:22