背景:jenkins-pipeline集成sonarqube代码扫描,根据代码检测的状态去判断是否继续执行流水线
环境:
jenkins插件:可根据执行报错自行下载(主要是我也忘了,操作很简单)
注意:具体安装可看devops专栏,docker-compose一键部署
jenkins-pipeline
//定义http方法
def HttpReq(reqType,reqUrl,reqBody){
// def sonarServer = "http://192.168.1.200:30090/api"
sonarServer = "http://192.168.100.231:9090/api"
// 可以不加authentication认证,因为默认不需要
result = httpRequest authentication: 'sonar-admin-user',
httpMode: reqType,
contentType: "APPLICATION_JSON",
consoleLogResponseBody: true,
ignoreSslErrors: true,
requestBody: reqBody,
url: "${sonarServer}/${reqUrl}"
//quiet: true
return result
}
//获取Sonar质量阈状态
def GetProjectStatus(projectName){
apiUrl = "project_branches/list?project=${projectName}"
response = HttpReq("GET",apiUrl,'')
response = readJSON text: """${response.content}"""
result = response["branches"][0]["status"]["qualityGateStatus"]
println(response)
return result
}
pipeline {
agent any
environment {
scannerPATH = "/var/jenkins_home/sonar-scanner/bin"
mvnPATH = "/var/jenkins_home/mvn/bin"
projectName = "${env.JOB_NAME}"
branchName = "master"
}
stages {
stage('pull code and make') {
// agent {
// docker {
// image 'maven:3-alpine'
// args '-v /root/.m2:/root/.m2'
// }
// }
steps {
git 'https://gitee.com/uuei/java-devops-demo.git'
sh """
${mvnPATH}/mvn -B -DskipTests clean package
"""
}
}
stage('sonar') {
steps {
script{
sonarDate = sh returnStdout: true, script: 'date +%Y%m%d%H%M%S'
sonarDate = sonarDate - "\n"
}
sh """
${scannerPATH}/sonar-scanner -Dsonar.projectKey=${projectName} \
-Dsonar.host.url=http://192.168.100.231:9090 \
-Dsonar.login=admin \
-Dsonar.password=admin \
-Dsonar.projectName=${projectName} -Dsonar.projectVersion=${sonarDate} -Dsonar.ws.timeout=30 \
-Dsonar.sources=src/main -Dsonar.sourceEncoding=UTF-8 -Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes -Dsonar.java.surefire.report=target/surefire-reports
"""
script{
result = GetProjectStatus("${projectName}")
if ("${result}" == "OK"){
println("代码检测通过 ")
}else{
error "代码检测不通过"
}
// println("${result}")
}
}
}
stage('Build') {
steps {
sh "docker build -t java-demo ."
}
}
}
}