How to react on SonarQube Quality Gate within Jenkins Pipeline

Christoph Forster picture Christoph Forster · Nov 9, 2016 · Viewed 18k times · Source

Within my Jenkins Pipeline I need to react on the SonarQube Quality Gate. Is there an easier way to achieve this but looking in the Sonar-Scanner log for the result page (e.g. https://mysonarserver/sonar/api/ce/task?id=xxxx) and parse the JSON Result from there?

I use Jenkins 2.30 and SonarQube 5.3

Thanks in advance

Answer

Tibo picture Tibo · Jul 27, 2017

Based on Vincent's answer, and using Pipeline utility steps, here's my updated version that worked for me (using sonarscanner report file) :

   withSonarQubeEnv('SONAR 6.4') {
                    sh "${scannerHome}/bin/sonar-scanner"
                    sh "cat .scannerwork/report-task.txt"
                    def props = readProperties  file: '.scannerwork/report-task.txt'
                    echo "properties=${props}"
                    def sonarServerUrl=props['serverUrl']
                    def ceTaskUrl= props['ceTaskUrl']
                    def ceTask
                    timeout(time: 1, unit: 'MINUTES') {
                        waitUntil {
                            def response = httpRequest ceTaskUrl
                            ceTask = readJSON text: response.content
                            echo ceTask.toString()
                            return "SUCCESS".equals(ceTask["task"]["status"])
                        }
                    }
                    def response2 = httpRequest url : sonarServerUrl + "/api/qualitygates/project_status?analysisId=" + ceTask["task"]["analysisId"], authentication: 'jenkins_scanner'
                    def qualitygate =  readJSON text: response2.content
                    echo qualitygate.toString()
                    if ("ERROR".equals(qualitygate["projectStatus"]["status"])) {
                        error  "Quality Gate failure"
                    }
                }

Please note the use of a Jenkins Credentials (authentication: 'jenkins_scanner') to retrieve the quality gate in Sonar being auhtenticated.