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

如何通过SonarQube api/measures/component API扫描多个项目?

SonarQube多项目指标查询解决方案

核心结论

api/measures/component 接口仅支持查询单个组件的指标,无法通过逗号分隔传递多个项目名称/key来批量查询,你需要换用以下方案:


方案1:循环调用单项目接口

在Groovy脚本里遍历目标项目列表,逐个调用api/measures/component接口,最后合并所有结果。

示例Groovy代码片段:

// 定义要查询的项目组件key列表(优先用key而非名称,避免匹配失败)
def targetProjects = ["project-key-1", "project-key-2", "project-key-3"]
def metricKeys = "bugs,vulnerabilities,code_smells"
def sonarBaseUrl = "http://your-sonar-server/api"
def authToken = "your-sonar-auth-token"

def allResults = []

targetProjects.each { projectKey ->
    // 构造请求URL
    def url = "${sonarBaseUrl}/measures/component?component=${projectKey}&metricKeys=${metricKeys}"
    // 发送请求(适配Jenkins环境的HTTP调用方式)
    def conn = new URL(url).openConnection()
    conn.setRequestProperty("Authorization", "Bearer ${authToken}")
    def result = new groovy.json.JsonSlurper().parse(conn.inputStream)
    // 收集项目指标结果
    allResults.add([project: projectKey, measures: result.component.measures])
}

// 处理合并后的结果
println allResults

SonarQube提供的api/measures/search接口支持批量查询多个组件的指标,只需通过componentKeys参数传递逗号分隔的项目key列表即可。

示例Groovy代码片段:

def projectKeys = "project-key-1,project-key-2,project-key-3"
def metricKeys = "bugs,vulnerabilities,code_smells"
def sonarBaseUrl = "http://your-sonar-server/api"
def authToken = "your-sonar-auth-token"

// 构造批量查询URL
def url = "${sonarBaseUrl}/measures/search?componentKeys=${projectKeys}&metricKeys=${metricKeys}"
def conn = new URL(url).openConnection()
conn.setRequestProperty("Authorization", "Bearer ${authToken}")
def result = new groovy.json.JsonSlurper().parse(conn.inputStream)

// 遍历输出各项目指标
result.components.each { component ->
    println "项目:${component.name},指标:${component.measures}"
}

关键注意事项

  • 确认项目component key:不要直接用项目名称,部分项目的名称与key不一致,可在SonarQube项目页面的URL末尾获取key(如id=xxx中的xxx)。
  • 权限检查:确保Jenkins使用的Sonar账号拥有所有目标项目的读取权限。
  • 分页处理:若查询项目数量较多,api/measures/search会返回分页结果,需通过p(页码)和ps(每页数量)参数处理分页逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:58:28