Gitlab 触发Jenkins 自动构建Sonar代码检测

GitLab配置

Project添加Webhook
http://192.168.21.207:8888//generic-webhook-trigger/invoke?token=quec-openapi&runOpts=GitlabPush
image.png

Sonar配置

添加网络调用
image.png

Jenkins配置

需要Generic Webhook Trigger插件
image.png

Pipline

  1. def createtime(){
  2. return new Date().format('yyyyMMddHHmm', TimeZone.getTimeZone("GMT+08:00"))
  3. }
  4. pipeline{
  5. agent any
  6. environment{
  7. git_key = "7b222e44-a44c-44cb-8581-eb0e6f394726"
  8. REPOSITORY = "http://192.168.21.204:8100/root/quec-openpai.git"
  9. }
  10. stages{
  11. stage("拉取代码"){
  12. steps{
  13. checkout([$class: 'GitSCM', branches: [[name: '${ref}']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: "${git_key}", url: "${REPOSITORY}"]]])
  14. echo "\033[44m 拉取成功 \033[0m"
  15. echo "${ref}"
  16. echo "Success!!!!"
  17. }
  18. }
  19. stage('静态代码检查') {
  20. steps {
  21. echo "starting codeAnalyze with SonarQube......"
  22. withSonarQubeEnv('sonar') {
  23. //注意这里withSonarQubeEnv()中的参数要与之前SonarQube servers中Name的配置相同
  24. withMaven(maven: 'maven') {
  25. 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"
  26. }
  27. }
  28. script {
  29. timeout(1) {
  30. //这里设置超时时间1分钟,不会出现一直卡在检查状态
  31. //利用sonar webhook功能通知pipeline代码检测结果,未通过质量阈,pipeline将会fail
  32. def qg = waitForQualityGate('sonar')
  33. //注意:这里waitForQualityGate()中的参数也要与之前SonarQube servers中Name的配置相同
  34. if (qg.status != 'OK') {
  35. error "未通过Sonarqube的代码质量阈检查,请及时修改!failure: ${qg.status}"
  36. }
  37. }
  38. }
  39. }
  40. }
  41. }
  42. }

效果

Git提交代码触发webhook,jenkins自动拉取代码 并提交Sonar代码扫描,扫描结果成功继续后续流程,失败直接Fail
image.png