How to fail a build after running sonarqube scanner

We are using SonarQube 7.9.4.

We are using the command-line sonar-scanner utility to scan our code as part of our build pipeline and the result gets uploaded to our SonarQube server. Is it possible for the scanner to return a failure status based on the quality gate so that we can use that and fail our pipeline? Currently we are not able to fail the build pipeline after a scan. We just periodically go to the SonarQube web interface and review and fix issues that get reported.

This all depends on how your pipeline is implemented. For instance, if you’re using a Jenkins scripted pipeline, you would be using the “withSonarQubeEnv()” and “waitForQualityGate()” pipeline steps. If the quality gate failed, you would get an error status back from the latter step, which tells your pipeline code to fail the build.

Thanks, David. We’re not using (and we can’t use) a Jenkins scripted pipeline. We’re simply running the sonar-scanner command-line utility as part of our build script.

Ok. This is still doable, it just requires performing manual steps that are usually taken care of by the infrastructure. Unfortunately, those steps require getting some details right.
At the completion of the “sonar:sonar” goal, you should have a “report-task.txt” file, very likely in “target/sonar/report-task.txt”. This is a Java properties file, which looks like this:

projectKey=...
serverUrl=...
serverVersion=...
branch=
dashboardUrl=...
ceTaskId=...
ceTaskUrl=...

Your build script is going to need to read this file. For these purposes, you only care about the value of the “ceTaskId” property. Using that, you’ll then need to reach the following endpoint in the sonarqube rest api: “/api/ce/task?id=${taskProps[‘ceTaskId’]}” . I suggest you examine the documentation for this endpoint in the rest api documentation (find the “Web Api” link at the bottom of your sonarqube web page). You’ll see that this has a “task.status” property that can be IN_PROGRESS, PENDING, ERROR, or SUCCESS (not certain about the spelling of the last two).

When the main scanning work is completed, the background task is started, so the initial state will likely be PENDING. What you’ll want to do is make this call in a loop with a sleep in between each call, waiting for the status to be other than IN_PROGRESS or PENDING. If it completes with an ERROR status, that means it failed the quality gate.

That sounds good. Thanks, David.