Right now, there’s no way to fail your pipeline in Azure DevOps (a.k.a Visual Studio Team Services, VSTS) when your SonarQube Quality Gate fails. To do this you have to call the SonarQube REST API from your pipeline. Here is a small tutorial how to do this.
Generate token
First you have to create a token in SonarQube. The token is used to call the API.
Add token as encrypted variable
In you pipeline you can now add the token as a variable. Make sure to encrypt it.
Add PowerShell task after “Publish Quality Gate Result”
Now add a new PowerShell task. Make it inline and add the following script:
$token = [System.Text.Encoding]::UTF8.GetBytes($env:SonarToken + ":") $base64 = [System.Convert]::ToBase64String($token) $basicAuth = [string]::Format("Basic {0}", $base64) $headers = @{ Authorization = $basicAuth } $result = Invoke-RestMethod -Method Get -Uri http://alegrisource.westeurope.cloudapp.azure.com/api/qualitygates/project_status?projectKey=alegri-cockpit20 -Headers $headers $result | ConvertTo-Json | Write-Host if ($result.projectStatus.status -eq "OK") { Write-Host "Quality Gate Succeeded" }else{ throw "Quality gate failed" }
Add a new Environment Variable called “SonarToken” with the value $(SonarToken).
That’s it. Now your pipeline will fail, if your quality gate fails.
Thanks for sharing!
Your first sentence probably was meant to start by “Right now, there’s no way…” or “Currently, there’s no way…” 😉
We Germans always put comas wrong in English 🙂
It is not about the comma. It should be „Right now“ instead of „Write now“.
Thanks for sharing.
“Facepalm” 🙂
Thanks for noticing me.
Does the URL in the Powershell need to be: http://alegrisource.westeurope.cloudapp.azure.com/api/qualitygates/project_status?projectKey=alegri-cockpit20
seems to be erroring at the moment if so?
You have to replace the URL with the URL of your SonarQube instance: https:///api/qualitygates/project_status?projectKey=
Thanks!
Hi , I am using SonarCloud , do you know where I can get the api Url? Thanks
You don’t need it. In SonarCoud you can use PullRequest decoration.
Thank you, currently I am using DevOps, I want the same process as yours just change the SonarQube to SonarCloud. But I didn’t find the relevant API to get the projectStatus to validate.
It’s better to use the status policy… Have you tried?
Is this what you want? Or do you really want to do it the other way? https://writeabout.net/2019/04/18/use-pull-request-decoration-in-azure-devops-with-sonarcloud/
Hi, great approach for Continuous Integration!!! i keep getting 401 unauthorized message, im new to powershell does someone have an idea on this?
Have you tried the script directly in PowerShell?
Ive tried that, i placed the script on a remote server, and still an issue 😦 im still getting a 401 from the remote server, it seems the Uri is ok but i do not know why its not getting the quality gate,
i think i got it working now, i missed a step lol ,
👍 What step did you miss?
the environment variable was not set under the task properly. i had a question. how would you configure it in tfs 2018? the script seems not to fit the dialog box for the powershell task. the one above is in AzureDevOps, thats working fine 🙂
If the script is too long you can add it in a file and include it in your repo…
currently im using a remote server to host my script ” *.ps1 ” for TFS so the powershell script is being shared for the task but i get this error , or what arguments do i need?
WS-Management could not connect to the specified destination:xxxx.xx:5986
Put the script in the repo and use the normal PowerShell task. There is no need to host the script remote – you are only calling an API…
Ah thanks, i think i over-complicated things, thanks for the explanation
Hi i was able to even go further with what you taught me, now we focus on new_security_rating to get new vulnerabilities
$security |
ForEach-Object {
if ($_ -eq “new_security_rating”)
{
$security = $_
$status = ($result.projectStatus.conditions | where { $_.metricKey -eq $security}).status
echo $status
if ($status -eq “OK”)
Nice
Hi Mike, great article. Thank you for sharing.
I just have a question about this approach. The source code will be sent to SonarQube right? If the quality gate fails, Sonar will maintain the previous state or will mantain with the failed status?
Thanks in advance.
Not the source code – but the analysis results. Yes. If you want support for branches (and pull requests) you need the developer edition or go to SonarCoud.
Hi Mike, quick update, improvised how to show the write-method message on the build logs and summary, but its still a work-in-progress 🙂
Build pipeline failed
2 error(s) / 11 warning(s)
Sonarqube Quality gate failed
At C:\BuildAgents\DevOpsVidlyBuild\devopsvidly\_temp\5246b10d-a13f-4709-984e-06
da31fb0fb9.ps1:13 char:1
+ throw “Sonarqube Quality gate failed”
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Sonarqube Quality gate failed
:String) [], RuntimeException
+ FullyQualifiedErrorId : Sonarqube Quality gate failed
Hi mike,
I have setup a Community Sonar Qube setup. I have analysed a project its has “E” grade for 3 of sonarway quality gate (default one). why in sonar qube server dashboard it is showing a status of “Passed” when actually it is getting “Worsed ” grade for some metrics.?? Failing the build in Azure dev-ops build is secondary to me in this case. First it should show that quality gates have failed.
Hi mike,
I have setup a Community Sonar Qube setup. I have analysed a project its has “E” grade for 3 of sonarway quality gate (default one). why in sonar qube server dashboard it is showing a status of “Passed” when actually it is getting “Worsed ” grade for some metrics.?? Failing the build in Azure dev-ops build is secondary to me in this case. First it should show that quality gates have failed.
What is this alegrisource??
http://alegrisource.westeurope.cloudapp.azure.com/api/qualitygates/project_status?projectKey=alegri-cockpit20
This request if failing for me
That’s the url of my SonarQube server in azure. Replace it with your server.
Hello,
I am getting this error:
char:188
+ … Basic {0}”, $base64), $headers = @{Authorization= $basicAuth}, $resul …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The assignment expression is not valid. The input to an assignment operator
must be an object that is able to accept assignments, such as a variable or a
property.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : InvalidLeftHandSide
##[error]PowerShell exited with code ‘1’.
##[section]Finishing: PowerShell
the url that i’m using is this one:
$result = Invoke-RestMethod -Method Get -Uri http://xx.xxx.xxx.xxx/api/qualitygates/project_status?projectKey=Test -Headers $headers
i just modified some parts of the link but i am not sure from where i can find the real link that we are using in the powershell script.