简单介绍
sonarqube 是一个代码质量检测平台,针对多宗语言进行代码质量分析。分为服务端和扫描的工具sonar-scanner。
sonarqube 版本很多,此处介绍的是它的长期支持版本7.9.5版本,此版本组建有server由elasticsearch 和web组成,内置默认数据库是H2,支持其他外部数据库(sqlserver、postgresql、orcale),7.9版本不再支持mysql 。
安装
server端安装
为了方便迁移构建了一个镜像,通过docker 启动server 和数据库postgresql,详见github
cli安装
下载压缩包到指定目录,使用版本为4.6.0,由于自带jre 所以不需要配置jdk等环境。
配置环境变量
cat /etc/profile
export SONAR_HOME=/home/ubuntu/sonar-scanner-4.6.0 export PATH=$PATH:$SONAR_HOME/bin
source /etc/profile
配置文件
#Configure here general information about the environment, such as SonarQube server connection details for example #No information about specific project should appear here #----- Default SonarQube server sonar.host.url=http://172.31.8.126:9000 #----- Default source code encoding sonar.sourceEncoding=UTF-8
使用示例
git 拉取一个java maven 编译的项目,在编译完成后代码扫描
root@sd-cluster-01:# ls
cicd mvnw mvnw.cmd pom.xml src target
vi scanner.sh
sonar-scanner -Dsonar.projectKey=my:test
-Dsonar.projectName=sonar-test
-Dsonar.projectVersion=v1.1
-Dsonar.sources=src
-Dsonar.java.binaries=target/classes
sh scanner.sh 执行扫描即可
参数介绍:
-Dsonar.projectKey 与项目名字一样即可
-Dsonar.projectName 项目名字
-Dsonar.projectVersion 版本,可以带一个时间戳
-Dsonar.sources 源码路径,一般java 项目都在src 目录,这里是没编译的源码文件
-Dsonar.java.binaries 要扫描编译后的类文件的目录
-Dsonar.host.url sonar server地址,上面没写是因为在配置文件中已经有了
Jenkins集成sonarqube
生成token
sonarqube web 界面生成一个token 用于在jenkins 中配置凭证,给jenkins集成的scanner作为认证信息
添加到jenkins 凭证
jenkins 安装插件
配置server 信息
系统管理》系统配置
添加server端信息,注意下面配置块只有在安装上面插件后生成,认证凭证需要稍后在sonarquebe中生成并且配置在jenkins 上面。
配置scanner
系统配置》全局工具配置
jenkins 任务使用示例
在构建后添加扫描操作,里面的参数参考上面的脚本扫描示例的介绍