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
- Jenkins: install the plugin, add the SonarQube server and token credential (Manage Jenkins → System).
- 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."
More on SonarQube
What is SonarQube and how do you integrate it into a pipeline?BeginnerWhat does SonarQube analyse?BeginnerHow do you run SonarQube locally with Docker?BeginnerHow do you scan a project with sonar-scanner?BeginnerHow do you run SonarQube analysis for a Maven project?BeginnerWhat is a quality gate in SonarQube?Beginner