在 GitLab CI 中集成 Quality Gate(质量门禁)时,可以在 SonarQube 上设置规则、阈值等要求,以确保代码的质量符合预期。具体步骤如下:
在 GitLab 中创建一个项目,并将项目代码托管到 GitLab 上;
在项目中添加一个 .gitlab-ci.yml 文件,并配置 sonar 分析任务;
打开 Sonar Web 界面,进入 Quality Gates 界面,在其中定义质量门禁规则;
在 .gitlab-ci.yml 文件中配置 sonar 分析任务时,添加 wait 和 qualitygate 参数,以便 GitLab CI 等待 SonarQube 的质量门禁结果。
例如:
sonarqube:
image: sonarsource/sonar-scanner-cli
script:
- sonar-scanner -Dsonar.qualitygate.wait=true -Dsonar.projectKey=my-project -Dsonar.sources=.
allow_failure: true
only:
- master
rules:
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: never
- when: always
changes:
- '**/*.js'
- '**/*.jsx'
- '**/*.ts'
- '**/*.tsx'
variables:
SONAR_HOST_URL: "http://my-sonar-server"
SONAR_LOGIN: $SONAR_TOKEN
SONAR_PROJECT_VERSION: "$CI_PIPELINE_ID"
# 添加 wait 和 qualitygate 参数
SONAR_QUALITYGATE_WAIT: "true"
SONAR_QUALITYGATE_INCLUSION_MODE: "all"
SONAR_QUALITYGATE_CONDITIONS: "coverage > 80, reliability_rating > 1, security_rating > 1"
以上示例中,指定了三个条件:覆盖率大于 80%,可靠性评级大于 1,安全性评级大于 1。如果代码的任何一个条件不符合预期,Quality Gate 任务将失败。
需要注意的是,阈值设置应根据实际情况进行调整,仅供参考。




