Gitlab 触发Jenkins 自动构建Sonar代码检测
GitLab配置
Project添加Webhook
http://192.168.21.207:8888//generic-webhook-trigger/invoke?token=quec-openapi&runOpts=GitlabPush
Sonar配置
Jenkins配置
需要Generic Webhook Trigger插件
Pipline
def createtime(){
return new Date().format('yyyyMMddHHmm', TimeZone.getTimeZone("GMT+08:00"))
}
pipeline{
agent any
environment{
git_key = "7b222e44-a44c-44cb-8581-eb0e6f394726"
REPOSITORY = "http://192.168.21.204:8100/root/quec-openpai.git"
}
stages{
stage("拉取代码"){
steps{
checkout([$class: 'GitSCM', branches: [[name: '${ref}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${git_key}", url: "${REPOSITORY}"]]])
echo "\033[44m 拉取成功 \033[0m"
echo "${ref}"
echo "Success!!!!"
}
}
stage('静态代码检查') {
steps {
echo "starting codeAnalyze with SonarQube......"
withSonarQubeEnv('sonar') {
//注意这里withSonarQubeEnv()中的参数要与之前SonarQube servers中Name的配置相同
withMaven(maven: 'maven') {
sh "mvn clean package -Dmaven.test.skip=true sonar:sonar -Dsonar.projectKey=Paas -Dsonar.projectName=quec-openapi -Dsonar.projectVersion=${ref} -Dsonar.sourceEncoding=UTF-8 -Dsonar.exclusions=src/test/** -Dsonar.sources=src/ -Dsonar.java.binaries=target/classes -Dsonar.host.url=http://192.168.21.244:9000 -Dsonar.login=16531a38c87b93facaf007152728009e2b1525df"
}
}
script {
timeout(1) {
//这里设置超时时间1分钟,不会出现一直卡在检查状态
//利用sonar webhook功能通知pipeline代码检测结果,未通过质量阈,pipeline将会fail
def qg = waitForQualityGate('sonar')
//注意:这里waitForQualityGate()中的参数也要与之前SonarQube servers中Name的配置相同
if (qg.status != 'OK') {
error "未通过Sonarqube的代码质量阈检查,请及时修改!failure: ${qg.status}"
}
}
}
}
}
}
}
效果
Git提交代码触发webhook,jenkins自动拉取代码 并提交Sonar代码扫描,扫描结果成功继续后续流程,失败直接Fail