Setup SonarQube with Jenkins Declarative Pipeline

Before start, you should have done…

  • Jenkins Multibranch Pipeline project setup with declarative pipeline Jenkinsfile. If not, please refer to this tutorial
  • sonar-project.properties file at your project root

Prerequisite

  • SonarQube Server
    Installation Guide: Link
    However, it’s easier to run a docker version, as always: Link
  • Jenskins Plugin: SonarQube Scanner for Jenkins

Setup

  • Create SonarQube User Token at SonarQube Server
    User > My Account > Security > Generate Tokens
Click the upper-right button [ A ] to expand the user dropdown, which took me a while to figure out where it is
  • Configurate SonarQube webhook for quality gate
    Administration > Configuration > Webhooks > Create
    The URL should point to your Jenkins server http://{JENKINS_HOST}/sonarqube-webhook/
  • Setup SonarQube server at Jenkins
    Manage Jenkins > Configure System > SonarQube servers
    Enter you SonarQube server host and the token generated at previous step
  • Setup SonarQube scanner at Jenkins
    Manage Jenkins > Global Tool Configuration > SonarQube Scanner
    Remember to give it a name, let’s take SonarQubeScanner as example here
  • Setup SonarQube scan stage in declarative pipeline Jenkinsfile
stage('Sonarqube') {
environment {
scannerHome = tool 'SonarQubeScanner'
}
steps {
withSonarQubeEnv('sonarqube') {
sh "${scannerHome}/bin/sonar-scanner"
}
timeout(time: 10, unit: 'MINUTES') {
waitForQualityGate abortPipeline: true
}
}
}

Noted that the tool name is the one you named for your SonarQube scanner at previous step

waitForQualityGate will halt the pipeline until SonarQube notifies Jenkins whether quality gate is passed through webhook setup earlier

Now you should see SonarQube in your pipeline, happy coding 🐤

Here we put SonarQube after testing stage for testing report collection, there are examples running SonarQube in parallel with testing stage. It’s all up to your need.

This post is tested with SonarQube 7.1 and Jenkins 2.121.3

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store