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

如何获取Jenkins multibranch pipeline关联的GitHub仓库地址(含脚本及API方法)

解决方案

一、调整Groovy脚本获取关联GitHub仓库

以下修改后的脚本可直接在Jenkins脚本控制台运行,输出所有多分支流水线及其关联的GitHub仓库信息:

import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject
import org.jenkinsci.plugins.github_branch_source.GitHubSCMSource

Jenkins.instance.getAllItems(WorkflowMultiBranchProject).each { job ->
    println "多分支任务路径:${job.fullName}"
    job.getSources().each { sourceItem ->
        def scmSource = sourceItem.getSource()
        if (scmSource instanceof GitHubSCMSource) {
            println "GitHub仓库:${scmSource.getRepoOwner()}/${scmSource.getRepository()}"
            println "HTTPS克隆地址:${scmSource.getHttpsUrl()}"
            println "SSH克隆地址:${scmSource.getSshUrl()}"
        }
        // 若使用通用Git源而非GitHub官方插件,替换上方if判断为以下逻辑
        /*
        if (scmSource instanceof jenkins.plugins.git.GitSCMSource) {
            println "Git仓库地址:${scmSource.getRemote()}"
        }
        */
    }
    println "----------------------------------------"
}

脚本运行需要Jenkins管理员权限,若存在单个多分支流水线关联多个仓库的场景,脚本会自动遍历输出所有关联仓库。

二、通过API调用获取信息

Jenkins原生支持REST API获取该配置数据,无需额外插件:

  • 单个多分支任务查询接口:GET https://<你的Jenkins域名>/job/<任务路径>/api/json,返回结果的sources字段中包含完整的仓库配置信息
  • 过滤返回字段精简请求(推荐):可在接口地址后加tree参数只拉取需要的SCM源信息,示例如下
curl -u <Jenkins用户名>:<用户API Token> "https://<你的Jenkins域名>/job/<多分支任务名>/api/json?tree=sources[source[repoOwner,repository,httpsUrl,sshUrl]]"
  • 批量查询逻辑:先调用全量任务列表接口拿到所有多分支流水线的路径,再逐个调用上述接口拉取对应仓库信息即可。
    用户API Token可在Jenkins个人设置页面生成,调用接口的用户需要持有对应任务的读权限。

内容的提问来源于stack exchange,提问作者10raw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:09:04