Verify SonarQube Code quality gate status, via a Jenkins declarative pipeline

This post will show how to return the status of a SonarQube code quality gate from a project.

Depending on the status returned you may want to fail the pipeline or continue.

The groovy uses curl along with a user token to call the SonarQube API which returns the quality gate of a specified SonarQube project.

sonar_status=`curl -s -u ${sonar_api_token}: <sonar_url>/api/qualitygates/project_status?projectKey=${sonar_project} | grep '{'       
    | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["'projectStatus'"]["'status'"];'`

echo "SonarQube status = $sonar_status"

Authentication

You will need to provide a form of authentication.

There are 2 options you can use:

Option 1: User token

How to Generate a Token

To generate a token, to go User > My Account > Security. Your existing tokens are listed here, each with a Revoke button.

The form at the bottom of the page allows you to generate new tokens. Once you click the Generate button, you will see the token value. Copy it immediately; once you dismiss the notification you will not be able to retrieve it.

Replace ${sonar_api_token} with your token.

Option 2: Basic access

Make use of your username and password for authentication.

The curl command shown earlier will require a slight tweak.

Replace: ${sonar_api_token}:

With:${your_username}:{your_password}

The full groovy code is here: https://gitlab.com/snippets/1942227

Last updated on 1 Oct 2019
Published on 1 Oct 2019