Fail your Azure DevOps pipeline if SonarQube Quality Gate fails

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.

Generate_Token_In_SonarQube

Add token as encrypted variable

In you pipeline you can now add the token as a variable. Make sure to encrypt it.

Add_encrypted_variable_for_token

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

Configure_PowerShell_Task

That’s it. Now your pipeline will fail, if your quality gate fails.

Result

35 thoughts on “Fail your Azure DevOps pipeline if SonarQube Quality Gate fails

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

  1. Hi, great approach for Continuous Integration!!! i keep getting 401 unauthorized message, im new to powershell does someone have an idea on this?

      1. 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,

      1. 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 🙂

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

      1. Ah thanks, i think i over-complicated things, thanks for the explanation

      2. 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”)

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

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

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

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

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

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

Leave a comment