持续集成交付CICD:Sonarqube自动更新项目质量配置
目录
一、实验
1.Sonarqube手动自定义质量规则并指定项目
2.Sonarqube自动更新项目质量配置
一、实验
1.Sonarqube手动自定义质量规则并指定项目
(1)自定义质量规则
①新配置
②更多激活规则③根据需求激活相应规则④已新增配置
⑤ 查看
(2)修改质量设置(添加项目)
①点击质量配置
②修改项目
③搜索并添加
④开始扫描
⑤ 质量规则已切换为指定的devops03
(3)项目添加质量配置
①移除绑定的项目
②右上角项目配置-质量配置
③修改配置
④指定一个质量配置
⑤开始扫描
⑥质量规则已切换为指定的devops03
2.Sonarqube自动更新项目质量配置
(1)查看gradle项目质量配置为空
(2)Postman发送
(3)gradle项目已新增质量配置
(4)修改流水线
pipeline {
agent { label "build"}
stages {
stage("Sonar"){
steps{
script {
projectName = "devops03-maven2-service"
lang = "java"
profileName = "devops03"
if (SearchProject(projectName)){
println("${projectName} exist")
} else {
//项目不存在
println("${projectName} not fonud")
//创建项目
CreateProject(projectName)
//质量配置
UpdateQualityProfiles(lang, projectName, profileName)
}
}
}
}
}
}
def SonarRequest(apiUrl,method){
withCredentials([string(credentialsId: "855da77c-ad38-4f06-a941-3a5afcf6bbc6", variable: 'SONAR_TOKEN')]) {
sonarApi = "http://192.168.204.8:9000/api"
response = sh returnStdout: true,
script: """
curl --location \
--request ${method} \
"${sonarApi}/${apiUrl}" \
--header "Authorization: Basic ${SONAR_TOKEN}"
"""
// json格式化
try {
response = readJSON text: """ ${response - "\n"} """
} catch(e){
response = readJSON text: """{"errors" : true}"""
}
return response
}
}
//查找项目
def SearchProject(projectName){
apiUrl = "projects/search?projects=${projectName}"
response = SonarRequest(apiUrl,"GET")
if (response.paging.total == 0){
return false
}
return true
}
//创建项目
def CreateProject(projectName){
apiUrl = "projects/create?name=${projectName}&project=${projectName}"
response = SonarRequest(apiUrl,"POST")
try{
if (response.project.key == projectName ) {
println("Project Create success!...")
return true
}
}catch(e){
println(response.errors)
return false
}
}
// 更新质量阈
def UpdateQualityProfiles(lang, projectName, profileName){
apiUrl = "qualityprofiles/add_project?language=${lang}&project=${projectName}&qualityProfile=${profileName}"
response = SonarRequest(apiUrl,"POST")
if (response.errors != true){
println("ERROR: UpdateQualityProfiles ${response.errors}...")
return false
} else {
println("SUCCESS: UpdateQualityProfiles ${lang} > ${projectName} > ${profileName}" )
return true
}
}
(5)任意项目进入回放运行
(6)成功
(7)sonarqube已新增maven2项目
(8)并自动实现质量配置
(9)本地代码扫描
sonar-scanner -Dsonar.host.url=http://192.168.204.8:9000 \
-Dsonar.projectKey=devops03-maven2-service \
-Dsonar.projectName=devops03-maven2-service \
-Dsonar.projectVersion=1.2 \
-Dsonar.login=admin \
-Dsonar.password=Admin123 \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="my first project" \
-Dsonar.links.homepage=http://192.168.204.8:82/devops03/devops03-maven5-service \
-Dsonar.links.ci=http://192.168.204.15:8080/job/devops03/job/devops03-maven-service/ \
-Dsonar.sources=src \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports
(10)maven2项目采用的质量阈为devops03