Chuyển tới nội dung

How to make SonarCloud fail from Azure Pipeline when Quality Gate failed.

As you know we were able to find a lot of articles to guide integration SonarCloud and Azure DevOps. However, When you want to make the Azure pipeline fail when the Quality Gate response fails from SonarCloud? Normally we will add a quality gate check in front of the Deployment step.

Today I will show you a script to call the API from SonarCloud and make the pipeline fail once the Quality gate fails. Let’s go.

- task: PowerShell@2
          displayName: 'Check Quality Gate Result '
          inputs:
            targetType: 'inline'
            script: |
              $token = [System.Text.Encoding]::UTF8.GetBytes("$(sonarcloud_token)" + ":")
              $base64 = [System.Convert]::ToBase64String($token)
              $branchSource = "$(Build.SourceBranch)"
              $branch = $branchSource -replace "refs/heads/", ""
              echo $branch
              $projectKey =  "Your project key"
              $basicAuth = [string]::Format("Basic {0}", $base64)
              $headers = @{ Authorization = $basicAuth }
              $result = Invoke-RestMethod -Method Get -Uri "https://sonarcloud.io/api/qualitygates/project_status?projectKey=$projectKey&branch=$branch" -Headers $headers
              $result | ConvertTo-Json | Write-Host
              if ($result.projectStatus.status -eq "OK") {
              Write-Host "Quality Gate Succeeded"
              }else{
              throw "Quality gate failed"
              }