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:
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.