Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

HTML
<div class="table-wrap"><table style="line-height: 1.4285715;" class="confluenceTable"><tbody><tr><td class="highlight-grey confluenceTd" data-highlight-colour="grey">By <a target="_top" href="httphttps://www.sonarsource.com">SonarSource</a> &#8211; GNU LGPL 3 &#8211;
<a target="_top" href="httphttps://jira.sonarsource.com/browse/SONARJNKNS">Issue Tracker</a> &#8211;
<a target="_top" href="https://github.com/SonarSource/jenkins-sonar-pluginscanner-jenkins">Sources</a>
<br>
<div>
    <div style="padding-top:10px;padding-bottom:5px">
    <span style="font-size:larger;"><strong>SonarQube Scanner for Jenkins 2.4<9</strong></span>
    <br>
    </div> 
</div> 
</div> </td></tr></tbody></table></div>

...

Info
iconfalse
titleTable of Contents

Table of Contents
maxLevel23

Features

You This plugin lets you centralize the configuration of SonarQube server connection details in Jenkins global configuration.

Then you can trigger SonarQube analysis from Jenkins using either a:

...

standard Jenkins Build Steps to trigger

...

analysis with

...

:

  • SonarQube Scanner (preferred)
  • Post-build action to trigger the analysis with Maven (SonarQube Scanner for Maven)
  • SonarQube Scanner for Gradle
  • SonarScanner for MSBuild

Once the job is complete, the plugin will detect that a SonarQube analysis was made during the build and display a badge and a widget on the job page with a link to the SonarQube dashboard as well as quality gate status.

Status
colourGreen
titleSince 2.5
 : you can also use Jenkins Pipeline DSL.

Compatibility

...

SonarQube Scanner for Jenkins

2.02.12.2.
1
x2.3 - 2.4.x2.52.62.7 - 2.9

Jenkins

1.344+1.491+1.580.1+1.
587
580.3+

Prerequisites

...

2.7.3+
2.32.2+2.89.4+

Status
colourGreen
titleSince 2.5
 Analysis must run with a JRE8

Installation

  1. Install the SonarQube Scanner for Jenkins via the Jenkins Update Center.

Server-level Configuration

Adding SonarQube Server

You can define as many SonarQube servers as you wish. Then for each Jenkins job, you will be able to choose which server to use for the SonarQube analysis.

To add a SonarQube server, just follow the three steps below:

 

  1. Configure your SonarQube server(s)
    1. Log into Jenkins as an administrator and go to Manage Jenkins > Configure System
    Image Removed
    1. Scroll down to the 
    SonarQube configuration
    1. SonarQube configuration section, click on 
    "
    1. Add SonarQube
    "
    1. , and add the values you're prompted for.
  2. For SonarQube servers at version 5.1 or lower, click on the "Advanced..." button and provide database credentials.

 

Adding SonarQube Scanner

Use

Analyzing with the SonarQube Scanner

Global Configuration

This step is mandatory if you want to trigger any of your SonarQube analyses with the SonarQube Scanner.   You can define as many SonarQube Scanner launchers scanner instances as you wish. Then for each Jenkins job, you will be able to choose with which launcher to use to run the SonarQube analysis.

To add a SonarQube Scanner:

  1. Log into Jenkins as an administrator and go to Manage Jenkins > Configure System:
    Image RemovedGlobal Tool Configuration
  2. Scroll down to the SonarQube RunnerScanner configuration section and click on Add SonarQube RunnerScanner. It is based on the typical Jenkins tool auto-installation. You can either choose to point to an already installed version of SonarQube Runner Scanner (uncheck 'Install automatically') or tell Jenkins to grab the installer from a remote location (check 'Install automatically'):
    Image Removed
Info

If you don't see a drop down list with all available SonarQube Runner Scanner versions but instead see an empty text field then this is because Jenkins still hasn't downloaded the required update center file (default period is 1 day). You may force this refresh by clicking 'Check Now' button in Manage Plugins >> > Advanced tab.

Job Configuration

  1. Configure the project, and scroll down to the Build section. 

Adding SonarQube Scanner for MSBuild

Refer to Jenkins section of in the SonarQube Scanner for MSBuild documentation.

Job-level Configuration

Configuring a SonarQube Scanner using environment variables

 

...

  1. Add the SonarQube Scanner build step to your build.
  2. Configure the SonarQube analysis properties. You can either point to an existing sonar-project.properties file or set the analysis properties directly in the Analysis properties field

Analyzing with SonarQube Scanner for MSBuild

Global Configuration

This step is mandatory if you want to trigger any of your analyses with the SonarQube Scanner for MSBuild. You can define as many scanner instances as you wish. Then for each Jenkins job, you will be able to choose with which launcher to use to run the SonarQube analysis.

  1. Log into Jenkins as an administrator and go to Manage Jenkins Global Tool Configuration

  2. Click on Add SonarQube Scanner for MSBuild

  3. Add an installation of the latest available version. Check Install automatically to have the SonarQube Scanner for MSBuild automatically provisioned on your Jenkins executors

    Tip

    If you do not see any available version under Install from GitHub, first go to Manage Jenkins > Manage Plugins > Advanced and click on Check now


Job Configuration

  1. Configure the project, and scroll down to the Build section.
  2. Add both the SonarQube for MSBuild - Begin Analysis and SonarQube for MSBuild - End Analysis build steps to your build
  3.  Configure the SonarQube Project KeyName and Version in the SonarQube Scanner for MSBuild - Begin Analysis build step
  4. Use the MSBuild build step or the Execute Windows batch command to execute the build with MSBuild 14 (see compatibility) between the Begin Analysis and End Analysis steps.
    Image Added


Analyzing with SonarQube Scanner for Maven or Gradle

Global Configuration

  1. Log into Jenkins as an administrator and go to Manage Jenkins > Configure System
  2. Scroll to the SonarQube servers section and check Enable injection of SonarQube server configuration as build environment variables

Job Configuration

  1. Configure the project, and scroll down to the Build Environment section.
  2. Enable Prepare SonarQube Scanner environment to allow the injection of SonarQube server values into this particular job. If multiple SonarQube instances are configured, you will be able to choose which one to use.

Image Removed

  1. Tip

    Press the help button to learn which variables you can use in your build.

...

You may then use any of the SonarQube Scanners to perform the analysis, such as Maven, Gradle, Ant, etc. An example using maven:

Image Removed

Analyzing

Analyzing with SonarQube Scanner for MSBuild

Refer to Jenkins section of in the SonarQube Scanner for MSBuild documentation.

Analyzing with the SonarQube Scanner

Go to the Build section, click on Add build step and choose Invoke Standalone SonarQube Analysis:

Image Removed

Configure the SonarQube analysis. You can either point to an existing sonar-project.properties file or set the analysis properties directly in the Project properties field:

Image Removed

Analyzing with SonarQube Scanner for Maven

Note
The Post-build Action for Maven analysis is deprecated.

Use the Build Environment option "Prepare SonarQube Scanner environment" (this option is only available if it has been enabled at the Global level by a Jenkins administrator) to inject SonarQube-related values as environment variables, such as:

  • SONAR_MAVEN_GOAL - defaults to sonar:sonar, but may vary depending on the sonar-maven-plugin specified for the selected SonarQube server
  • SONAR_HOST_URL

Use the help icon ((question)) to see the full list of available variables. Some values will be blank, depending on what was defined for the server.

Once the environment variables are available, use them in a standard Maven build step:

Image Removed

  1. Some values may be blank, depending on what was defined for the server.

    Image Added





  2. Once the environment variables are available, use them in a standard Maven build step (Invoke top-level Maven targets) by setting the Goals to include, or a standard Gradle build step (Invoke Gradle script) by setting the Tasks to execute:

    Code Block
    languagebash
    titleMaven goal
    $SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL


    Code Block
    languagebash
    titleGradle task
    sonarqube -Dsonar.host.url=$SONAR_HOST_URL

    In both cases, launching your analysis may require authentication. In that case, make sure that the Global Configuration defines a valid SonarQube token, and add it to the Maven goal or Gradle task with the following argument and value: -Dsonar.login=$SONAR_AUTH_TOKEN


Note
The Post-build Action for Maven analysis is still available, but is deprecated.

Analyzing in a Jenkins pipeline

Since version 2.5 of the SonarQube Scanner for Jenkins, there is an official support of Jenkins pipeline. We provide a 'withSonarQubeEnv' block that allow to select the SonarQube server you want to interact with. Connection details you have configured in Jenkins global configuration will be automatically passed to the scanner.

Note

Support of pipeline only works with SonarQube >= 5.2.

Here are a some examples for every scanner, assuming you run on Unix slaves and you have configured a server named 'My SonarQube Server' as well as required tools. If you run on Windows slaves, just replace 'sh' by 'bat'.

Code Block
languagegroovy
titleSonarQube Scanner
node {
  stage('SCM') {
    git 'https://github.com/foo/bar.git'
  }
  stage('SonarQube analysis') {
    // requires SonarQube Scanner 2.8+
    def scannerHome = tool 'SonarQube Scanner 2.8';
    withSonarQubeEnv('My SonarQube Server') {
      sh "${scannerHome}/bin/sonar-scanner"
    }
  }
}


Code Block
languagegroovy
titleSonarQube Scanner for Gradle
node {
  stage('SCM') {
    git 'https://github.com/foo/bar.git'
  }
  stage('SonarQube analysis') {
    withSonarQubeEnv('My SonarQube Server') {
      // requires SonarQube Scanner for Gradle 2.1+
      // It's important to add --info because of SONARJNKNS-281
      sh './gradlew --info sonarqube'
    }
  }
}


Code Block
languagegroovy
titleSonarQube Scanner for Maven
node {
  stage('SCM') {
    git 'https://github.com/foo/bar.git'
  }
  stage('SonarQube analysis') {
    withSonarQubeEnv('My SonarQube Server') {
      // requires SonarQube Scanner for Maven 3.2+
      sh 'mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar'
    }
  }
}


Code Block
languagegroovy
titleSonarQube Scanner for MSBuild
node {
  stage('SCM') {
    git 'https://github.com/foo/bar.git'
  }
  stage('Build + SonarQube analysis') {
    def sqScannerMsBuildHome = tool 'Scanner for MSBuild 2.2'
    withSonarQubeEnv('My SonarQube Server') {
      // Due to SONARMSBRU-307 value of sonar.host.url and credentials should be passed on command line
      bat "${sqScannerMsBuildHome}\\SonarQube.Scanner.MSBuild.exe begin /k:myKey /n:myName /v:1.0 /d:sonar.host.url=%SONAR_HOST_URL% /d:sonar.login=%SONAR_AUTH_TOKEN%"
      bat 'MSBuild.exe /t:Rebuild'
      bat "${sqScannerMsBuildHome}\\SonarQube.Scanner.MSBuild.exe end /d:sonar.login=%SONAR_AUTH_TOKEN%"
    }
  }
}

Pause pipeline until quality gate is computed

The waitForQualityGate step will pause the pipeline until SonarQube analysis is completed and returns quality gate status.

Pre-requisites:

  • SonarQube server 6.2+ (need webhook feature)
  • Configure a webhook in your SonarQube server pointing to <your Jenkins instance>/sonarqube-webhook/ (info) The trailing slash is mandatory with SonarQube 6.2 and 6.3!
  • Use withSonarQubeEnv step in your pipeline (so that SonarQube taskId is correctly attached to the pipeline context).

Example (scripted pipeline):

Code Block
languagegroovy
titleWait for Quality Gate under Maven (scripted)
node {
  stage('SCM') {
    git 'https://github.com/foo/bar.git'
  }
  stage('SonarQube analysis') {
    withSonarQubeEnv('My SonarQube Server') {
      sh 'mvn clean package sonar:sonar'
    } // SonarQube taskId is automatically attached to the pipeline context
  }
}
 
// No need to occupy a node
stage("Quality Gate"){
  timeout(time: 1, unit: 'HOURS') { // Just in case something goes wrong, pipeline will be killed after a timeout
    def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
    if (qg.status != 'OK') {
      error "Pipeline aborted due to quality gate failure: ${qg.status}"
    }
  }
}

Thanks to the webhook, the step is implemented in a very lightweight way: no need to occupy a node doing polling, and it doesn't prevent Jenkins to restart (step will be restored after restart). Note that to prevent race conditions, when the step starts (or is restarted) a direct call is made to the server to check if the task is already completed.

Example (declarative pipeline):

Code Block
languagegroovy
titleWait for Quality Gate under Maven (declarative)
pipeline {
    agent any
    stages {
        stage('SCM') {
            steps {
                git url: 'https://github.com/foo/bar.git'
            }
        }
        stage('build && SonarQube analysis') {
            steps {
                withSonarQubeEnv('My SonarQube Server') {
				    // Optionally use a Maven environment you've configured already
                    withMaven(maven:'Maven 3.5') {
                        sh 'mvn clean package sonar:sonar'
                    }
                }
            }
        }
        stage("Quality Gate") {
            steps {
                timeout(time: 1, unit: 'HOURS') {
					// Parameter indicates whether to set pipeline to UNSTABLE if Quality Gate fails
					// true = set pipeline to UNSTABLE, false = don't
					// Requires SonarQube Scanner for Jenkins 2.7+
                    waitForQualityGate abortPipeline: true
                }
            }
        }
    }
}
  • If you want to run multiple analysis in the same pipeline and use waitForQualityGate, it works starting from version 2.8, but you have to do everything in order:
Code Block
languagegroovy
titleMultiple analyses
pipeline {
    agent any
    stages {
        stage('SonarQube analysis 1') {
            steps {
                sh 'mvn clean package sonar:sonar'
            }
        }
        stage("Quality Gate 1") {
            steps {
                waitForQualityGate abortPipeline: true
            }
        }
        stage('SonarQube analysis 2') {
            steps {
                sh 'gradle sonarqube'
            }
        }
        stage("Quality Gate 2") {
            steps {
                waitForQualityGate abortPipeline: true
            }
        }
    }
}