How do you make a Jenkins pipeline fail when the SonarQube quality gate fails?

IntermediateHands-onSonarQube
Answer

Short answer

Use the SonarQube Scanner for Jenkins plugin: run the analysis inside withSonarQubeEnv, then call waitForQualityGate abortPipeline: true. SonarQube sends the result back through a webhook to Jenkins, and the stage fails if the gate fails.

Jenkinsfile

pipeline {
  agent any
  tools { maven 'maven-3.9'; jdk 'jdk-21' }
  stages {
    stage('Build & test') {
      steps { sh 'mvn -B clean verify' }
    }
    stage('SonarQube analysis') {
      steps {
        withSonarQubeEnv('sonarqube') {            // server configured in Manage Jenkins
          sh 'mvn -B sonar:sonar -Dsonar.projectKey=orders-service'
        }
      }
    }
    stage('Quality gate') {
      steps {
        timeout(time: 5, unit: 'MINUTES') {
          waitForQualityGate abortPipeline: true
        }
      }
    }
  }
}

Setup needed

  1. Jenkins: install the plugin, add the SonarQube server and token credential (Manage Jenkins → System).
  2. SonarQube: Administration → Webhooks → add https://jenkins.company.com/sonarqube-webhook/.

If it hangs

The webhook isn't reaching Jenkins (network, wrong URL) — the timeout prevents waiting forever.

What to say in the interview

"withSonarQubeEnv injects the server and token, the scan uploads results, and waitForQualityGate with abortPipeline true waits for SonarQube's webhook and fails the build on a red gate. A timeout guards against a missing webhook."

All Security Tools questions Roadmap: SonarQube — code quality & SAST

More on SonarQube