Purpose
jenkins Just create one job,git Automatically after push sonar The code is detected and uploaded to sonarqube
jenkins plug-in unit
Basic plug-ins have been installed as recommended by the community
- Generic Webhook Trigger
- SonarQube Scanner
preparation
sonar To generate the token
After logging in, click " Head portrait > My account number > Security "
Generate token and Copy and save
Add token to jenkins In the voucher “ System management > Management Certificates > Add credentials ”
Type selection Secret text
Paste the token into Secret In the box ,ID And description can be set as desired
jenkins add to SonarQube Server “ System management > The system configuration > SonarQube servers”
Definition name And sonarqube Address , Select the voucher just created , Click save ( here name I named ‘SonarQube’)
jenkins add to Sonar Scanner “ System management > Global tool configuration > SonarQube Scanner”
Definition name, Check auto install , Select the latest version , Click save
establish jenkins job
newly build job, Choose pipeline
“ Build trigger ” Choose "Generic Webhook Trigger"
- Copy http://JENKINS_URL/generic-webhook-trigger/invoke spare , As trigger address (JENKINS_URL Need to replace with your own jenkins Address )
- Post content parameters Extract the required parameters
- github as follows
variable expression expressionType defaultValue regexpFilter project_name $.repository.name JSONPath ssh_url $.repository.ssh_url JSONPath ref $.ref JSONPath - gitlab as follows
variable expression expressionType defaultValue regexpFilter project_name $.project.name JSONPath ssh_url $.project.git_ssh_url JSONPath ref $.ref JSONPath - Definition Token, Different token Can trigger different job( if token The same triggers multiple job)
Definition Assembly line
pipeline { agent any stages { stage('Check Out!') { steps { script { // Parse Branch arr = "${env.ref}".split("refs/heads/") as List currentBranch = arr[1] } git branch: currentBranch, credentialsId: '343aa12a-92a3-4797-a9ea-a8facb4db380', url: '${ssh_url}' //credentialsId by ssh Private key , For pulling git Code } } stage('Sonar Scan!') { steps { script { sonarqubeScannerHome = tool name: 'SonarQube Scanner' // Preparatory work No 4 Step by step name withSonarQubeEnv('SonarQube') { // Preparatory work No 3 Step by step name, Only one time can be omitted sh """ ${sonarqubeScannerHome}/bin/sonar-scanner \ -Dsonar.projectKey=${project_name} \ -Dsonar.projectName=${project_name} \ -Dsonar.sources=./ """ } } } } } }
Definition webhook(github For example )
Open the project "Settings > Webhooks"
write in url And create job The second step token( Be careful token stay url after )
verification
- Trigger push After the event , You can see jenkins Begin to build , After completion sonarqube Relevant reports can also be seen on the platform