GitLab集成SonarQube使用和配置
1、界面设置为简体中文
通过管理页面安装汉化包
进入Administration菜单,选择Marketplace。找到Chinese Pack安装即可

2、普通用户添加:配置-权限-用户

3、从gitlab导入项目
选择“导入GitLab”

在gitlab中创建个人令牌,选择范围包含API和read_api

sonarqube中输入gitlab生成的个人令牌,就可以看到gitlab中的项目列表,选择一个项目


4、配置分析器,使用GitLab CI


①定义gitlab环境变量:SONAR_TOKEN和SONAR_HOST_URL



②根据指引创建配置sonar文件sonar-project.properties并粘贴projectKey配置,当然你也可以添加更多配置,这里的projectKey主要用于和sonarqube通信,不配置扫描会报权限问题。

③编辑.gitlab-ci.yml文件添加sonarqube扫描脚本,以下使用shell执行器

variables:
SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar" # Defines the location of the analysis task cache
GIT_DEPTH: "0" # Tells git to fetch all the branches of the project, required by the analysis task
stages:
- build-sonar
build-sonar:
stage: build-sonar
cache:
policy: pull-push
key: "sonar-cache-$CI_COMMIT_REF_SLUG"
paths:
- "${SONAR_USER_HOME}/cache"
- sonar-scanner/
script:
- sonar-scanner -Dsonar.host.url="${SONAR_HOST_URL}"
allow_failure: true
rules:
- if: $CI_COMMIT_BRANCH == 'develop'如果使用Shell执行器,需要在gitlab-runner所在主机上安装sonar-scanner:不然会遇到“sonar-scanner:未找到命令”(注意不要安装在sonar主机上)
# 下载并解压到 /opt wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.8.0.2856-linux.zip unzip sonar-scanner-cli-*.zip -d /opt/ mv /opt/sonar-scanner-* /opt/sonar-scanner # 设置环境变量 echo 'export SONAR_SCANNER_HOME="/opt/sonar-scanner"' >> ~/.bashrc echo 'export PATH="$SONAR_SCANNER_HOME/bin:$PATH"' >> ~/.bashrc source ~/.bashrc # 验证安装 sonar-scanner --version
特别注意:sonar-scanner的版本支持的java版本要和sonarqube的java版本一致,不然扫描会报版本兼容问题,具体可以参考下面链接选择适合的sonarscanner版本
https://docs.sonarsource.com/sonarqube-server/latest/analyzing-source-code/scanners/sonarscanner/
官方给出的例子使用docker执行器,自己可以尝试,前提是你的runner执行器是docker执行器。
image:
name: sonarsource/sonar-scanner-cli:11
entrypoint: [""]
variables:
SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar" # Defines the location of the analysis task cache
GIT_DEPTH: "0" # Tells git to fetch all the branches of the project, required by the analysis task
stages:
- build-sonar
build-sonar:
stage: build-sonar
cache:
policy: pull-push
key: "sonar-cache-$CI_COMMIT_REF_SLUG"
paths:
- "${SONAR_USER_HOME}/cache"
- sonar-scanner/
script:
- sonar-scanner -Dsonar.host.url="${SONAR_HOST_URL}"
allow_failure: true
rules:
- if: $CI_PIPELINE_SOURCE == 'merge_request_event'
- if: $CI_COMMIT_BRANCH == 'master'
- if: $CI_COMMIT_BRANCH == 'main'
- if: $CI_COMMIT_BRANCH == 'develop'另外也可以根据自己情况决定是否单独创建配置文件sonar-project.properties来设置更多个性化配置
- 本文固定链接: http://ttfde.top/index.php/post/448.html
- 转载请注明: admin 于 TTF的家园 发表
《本文》有 0 条评论