如何在 DSL 中调用 REST API 获取 SonarQube Project Key 并写入 `properties`?
解读
国内 Jenkins 面试中,“Pipeline-as-Code + 质量门禁” 是高频考点。
题目表面问“取 key 写文件”,实质考察:
- Groovy 脚本安全沙箱 与 REST 调用 的平衡;
- SonarQube 6.7 LTS 及以上版本 的
/api/components/search接口鉴权方式(国内大部分公司用 7.9/8.9 LTS); - 多分支流水线 下,项目 key 可能含
/需 URL 编码; - properties 文件 最终要被 SonarScanner 读取,必须落盘到 workspace,且不能污染 git 工作区。
知识点
- HttpRequest 插件:官方推荐,沙箱白名单,支持 Jenkins 凭据体系;
- SonarQube Project Key 生成规则:
- Maven:
groupId:artifactId; - Gradle/自由风格:手动指定
sonar.projectKey; - 多分支:
{key}:{branch},需URLEncoder.encode(branch,'UTF-8');
- Maven:
- Jenkins 凭据存储:国内公司普遍开启 Role Strategy + 文件夹级凭据,需用
withCredentials绑定 token; - Pipeline 沙箱:
java.net.HttpURLConnection会被拒绝,必须 使用插件或共享库封装; - properties 文件格式:
key=value\n,注意 无空格,否则 SonarScanner 解析失败; - 幂等性:重复构建时,覆盖写 而非追加,防止旧分支 key 残留。
答案
// Jenkinsfile(Declarative 内嵌 script,沙箱开启)
pipeline {
agent any
options {
buildDiscarder(logRotator(numToKeepStr: '5'))
}
environment {
// 在 Jenkins 凭据里存放 SonarQube token,ID 为 'sonar-token'
SONAR_TOKEN = credentials('sonar-token')
SONAR_HOST = 'https://sonar.xxx.com'
// 项目唯一标识,可按需替换为 ${env.REPO_NAME}
REPO_KEY = 'com.xxx:order-service'
}
stages {
stage('Compute Sonar ProjectKey') {
steps {
script {
// 多分支场景,把分支名编码
def branch = URLEncoder.encode(env.GIT_BRANCH, 'UTF-8')
def api = "/api/components/search?qualifiers=TRK&q=${REPO_KEY}"
def url = "${SONAR_HOST}${api}"
// 使用 HttpRequest 插件,自动走 Jenkins 代理配置
def response = httpRequest(
url: url,
httpMode: 'GET',
authentication: env.SONAR_TOKEN,
validResponseCodes: '200',
consoleLogResponseBody: false // 防止泄露
)
// 解析 JSON,国内很多公司停留在 6.7,字段名仍为 components[0].key
def json = readJSON text: response.content
if (json.components.isEmpty()) {
error "SonarQube 未找到项目:${REPO_KEY}"
}
def projectKey = json.components[0].key + ":" + branch
// 写入 sonar-project.properties,供下一步 SonarScanner 读取
writeFile file: 'sonar-project.properties',
text: "sonar.projectKey=${projectKey}\n" +
"sonar.projectName=${REPO_KEY}\n" +
"sonar.projectVersion=${env.BUILD_NUMBER}\n"
// 回显供面试官观察
echo "Detected Sonar ProjectKey: **${projectKey}**"
}
}
}
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('SonarQube') {
sh 'sonar-scanner'
}
}
}
}
}
关键细节:
- 用
HttpRequest插件,无需额外批准; - 用
credentials()绑定,不落盘明文 token; - 文件必须写在 当前 workspace,否则
sonar-scanner找不到; - 若公司用 社区版 8.9,接口返回字段相同,无需调整。
拓展思考
- 共享库封装:把取 key 逻辑放到
vars/sonarKey.groovy,全公司统一,面试可提“我们维护了内部共享库,版本化发布”; - 质量门禁:下一步调用
/api/qualitygates/project_status?projectKey=xxx获取 quality gate,若status=ERROR直接currentBuild.result='FAILURE',国内金融公司强制要求; - 缓存优化:项目 key 不会频繁变化,可在 第一次构建 后把 key 存到 Jenkins 自定义属性(
currentBuild.description或InfluxDB),减少一次 HTTP; - 国产化场景:若公司用 腾讯/阿里 Sonar 托管版,域名带
.internal,需配置 Jenkins 代理白名单 与 自签证书信任库,面试可展示“我们给 Jenkins 装了公司根证书到$JAVA_HOME/jre/lib/security/cacerts”; - 安全合规:国内 等保 2.0 要求最小权限,Sonar token 只给 浏览权限,不授予执行权限,面试可强调“我们按最小权限定期审计”。