Fail your Azure DevOps pipeline if SonarQube Quality Gate fails

Right now, there’s now 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 -Headers $headers
$result | ConvertTo-Json | Write-Host

if ($result.projectStatus.status -eq "OK") {
Write-Host "Quality Gate Succeeded"
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.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s