Integrate SonarQube with Jenkins pipeline for automated code quality checks

Intermediate 25 min Apr 25, 2026 142 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up continuous code quality analysis by integrating SonarQube with Jenkins CI/CD pipelines. This tutorial covers SonarQube Scanner installation, webhook configuration, quality gates, and automated reporting for enforcing code standards across your development workflow.

Prerequisites

  • Jenkins server with admin access
  • SonarQube server running
  • Java project with Maven or Gradle build

What this solves

Integrating SonarQube with Jenkins automates code quality analysis in your CI/CD pipeline, catching bugs, security vulnerabilities, and code smells before they reach production. This setup enforces quality gates that can fail builds when code doesn't meet your standards, providing immediate feedback to developers and maintaining consistent code quality across your entire codebase.

Step-by-step configuration

Install SonarQube Scanner on Jenkins

Install the SonarQube Scanner plugin and configure the scanner tool in Jenkins. This provides the integration between Jenkins and your SonarQube server.

wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-5.0.1.3006-linux.zip
unzip sonar-scanner-cli-5.0.1.3006-linux.zip
sudo mv sonar-scanner-5.0.1.3006-linux /opt/sonar-scanner
sudo ln -s /opt/sonar-scanner/bin/sonar-scanner /usr/local/bin/sonar-scanner
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-5.0.1.3006-linux.zip
unzip sonar-scanner-cli-5.0.1.3006-linux.zip
sudo mv sonar-scanner-5.0.1.3006-linux /opt/sonar-scanner
sudo ln -s /opt/sonar-scanner/bin/sonar-scanner /usr/local/bin/sonar-scanner

Configure SonarQube Scanner in Jenkins

Add the SonarQube Scanner installation to Jenkins global tool configuration so pipelines can use it.

  1. Navigate to Jenkins Dashboard → Manage Jenkins → Global Tool Configuration
  2. Scroll to SonarQube Scanner section
  3. Click "Add SonarQube Scanner"
  4. Set Name: SonarQubeScanner
  5. Set SONAR_RUNNER_HOME: /opt/sonar-scanner
  6. Click "Save"

Create SonarQube authentication token

Generate a token in SonarQube that Jenkins will use for authentication during analysis.

  1. Log into your SonarQube web interface
  2. Go to User → My Account → Security
  3. Generate a new token with name jenkins-integration
  4. Copy the generated token (you won't see it again)

Configure SonarQube server in Jenkins

Add your SonarQube server details and authentication token to Jenkins system configuration.

  1. Navigate to Jenkins Dashboard → Manage Jenkins → Configure System
  2. Scroll to SonarQube servers section
  3. Click "Add SonarQube"
  4. Set Name: SonarQube
  5. Set Server URL: http://your-sonarqube-server:9000
  6. Add credentials with the token from previous step
  7. Click "Save"

Configure SonarQube webhook

Set up a webhook so SonarQube can notify Jenkins when analysis is complete, enabling quality gate checks.

curl -u admin:admin -X POST "http://your-sonarqube-server:9000/api/webhooks/create" \
  -d "name=jenkins-webhook" \
  -d "url=http://your-jenkins-server:8080/sonarqube-webhook/"

Create sonar-project.properties file

Add project configuration file to your source code repository to define analysis parameters.

sonar.projectKey=your-project-key
sonar.projectName=Your Project Name
sonar.projectVersion=1.0
sonar.sources=src
sonar.language=java
sonar.sourceEncoding=UTF-8
sonar.java.binaries=target/classes
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml

Create Jenkins pipeline with SonarQube integration

Configure a Jenkins pipeline that runs SonarQube analysis and checks quality gates as part of your CI/CD process.

pipeline {
    agent any
    
    environment {
        SCANNER_HOME = tool 'SonarQubeScanner'
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        
        stage('Build') {
            steps {
                sh 'mvn clean compile'
            }
        }
        
        stage('Test') {
            steps {
                sh 'mvn test'
                publishTestResults testResultsPattern: 'target/surefire-reports/*.xml'
            }
        }
        
        stage('SonarQube Analysis') {
            steps {
                withSonarQubeEnv('SonarQube') {
                    sh '${SCANNER_HOME}/bin/sonar-scanner'
                }
            }
        }
        
        stage('Quality Gate') {
            steps {
                timeout(time: 1, unit: 'HOURS') {
                    waitForQualityGate abortPipeline: true
                }
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh 'mvn deploy'
            }
        }
    }
    
    post {
        always {
            publishHTML([
                allowMissing: false,
                alwaysLinkToLastBuild: true,
                keepAll: true,
                reportDir: 'target/site/jacoco',
                reportFiles: 'index.html',
                reportName: 'Coverage Report'
            ])
        }
        failure {
            mail to: 'team@example.com',
                 subject: "Failed Pipeline: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
                 body: "Build failed. Check console output at ${env.BUILD_URL}"
        }
    }
}

Configure quality gates in SonarQube

Set up quality gate rules that define when a build should pass or fail based on code quality metrics.

  1. In SonarQube, go to Quality Gates → Create
  2. Name it Strict Gate
  3. Add conditions:
    • Coverage on New Code: Minimum 80%
    • Duplicated Lines on New Code: Maximum 3%
    • Security Rating on New Code: Grade A
    • Reliability Rating on New Code: Grade A
    • Maintainability Rating on New Code: Grade A
  4. Set as default quality gate

Configure branch analysis

Enable branch and pull request analysis for comprehensive code quality checking across all development branches.

sonar.projectKey=your-project-key
sonar.projectName=Your Project Name
sonar.sources=src
sonar.java.binaries=target/classes
sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml

Branch analysis

sonar.pullrequest.provider=github sonar.pullrequest.github.repository=your-org/your-repo

Set up automated reporting

Configure Jenkins to generate and archive quality reports after each analysis for tracking trends over time.

post {
    always {
        script {
            def sonarqubeUrl = "http://your-sonarqube-server:9000"
            def projectKey = "your-project-key"
            
            // Generate quality report
            sh """
                curl -u ${SONAR_AUTH_TOKEN}: \
                "${sonarqubeUrl}/api/measures/component?component=${projectKey}&metricKeys=coverage,duplicated_lines_density,reliability_rating,security_rating,sqale_rating" \
                > sonarqube-metrics.json
            """
            
            archiveArtifacts artifacts: 'sonarqube-metrics.json', fingerprint: true
        }
    }
}

Configure advanced quality rules

For enterprise environments with multiple projects, you'll want to configure custom quality profiles and rules. This builds on the SonarQube quality gates configuration to enforce consistent standards across teams.

Create custom quality profile

Set up project-specific quality profiles with custom rules that match your coding standards and security requirements.

  1. In SonarQube, navigate to Quality Profiles
  2. Select your language (e.g., Java)
  3. Click "Create" and name it Enterprise Java
  4. Inherit from "Sonar way" profile
  5. Add custom rules for:
    • Maximum method complexity: 10
    • Maximum file length: 500 lines
    • Mandatory code comments on public methods
    • Required unit test coverage: 80%
  6. Set as default for your project

Configure pipeline notifications

Set up Slack or email notifications for quality gate failures to ensure immediate team visibility of code quality issues.

post {
    failure {
        script {
            if (currentBuild.result == 'FAILURE' && env.STAGE_NAME == 'Quality Gate') {
                slackSend(
                    channel: '#dev-team',
                    color: 'danger',
                    message: "Quality Gate Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}\nSonarQube Report: http://your-sonarqube-server:9000/dashboard?id=your-project-key"
                )
            }
        }
    }
    success {
        script {
            if (env.BRANCH_NAME == 'main') {
                slackSend(
                    channel: '#dev-team',
                    color: 'good',
                    message: "✅ Quality Gate Passed: ${env.JOB_NAME} deployed to production"
                )
            }
        }
    }
}

Verify your setup

# Verify SonarQube Scanner installation
sonar-scanner --version

Test SonarQube server connection

curl -u your-token: http://your-sonarqube-server:9000/api/system/status

Verify Jenkins can reach SonarQube

curl -I http://your-jenkins-server:8080/sonarqube-webhook/

Check webhook configuration

curl -u admin:admin "http://your-sonarqube-server:9000/api/webhooks/list"

Verify quality gate status for project

curl -u your-token: "http://your-sonarqube-server:9000/api/qualitygates/project_status?projectKey=your-project-key"
Note: Replace your-token, your-sonarqube-server, your-jenkins-server, and your-project-key with your actual values.

Common issues

SymptomCauseFix
Quality gate never completesWebhook not configured properlyVerify webhook URL in SonarQube admin settings and Jenkins accessibility
Scanner not found errorSonarQube Scanner not in PATHCheck tool configuration in Jenkins and verify /opt/sonar-scanner installation
Authentication failedInvalid or expired tokenRegenerate SonarQube token and update Jenkins credentials
Project not found in SonarQubeWrong project key in propertiesVerify sonar.projectKey matches exactly with SonarQube project
Coverage reports not showingWrong path to coverage XMLUpdate sonar.coverage.jacoco.xmlReportPaths to correct file location
Pipeline hangs on quality gateWebhook delivery failureCheck Jenkins logs and ensure Jenkins URL is accessible from SonarQube server
Security note: Store SonarQube tokens as Jenkins credentials, not in plain text. Use HTTPS for production SonarQube servers and enable proper authentication.

Next steps

Running this in production?

Want this handled for you? Setting this up once is straightforward. Keeping it patched, monitored, backed up and tuned across environments is the harder part. See how we run infrastructure like this for European SaaS and e-commerce teams.

Need help?

Don't want to manage this yourself?

We handle managed devops services for businesses that depend on uptime. From initial setup to ongoing operations.