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.

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

8 comments

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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