David Parra
David Parra

Reputation: 111

Force to fail a sonarqube job in gitlab CI

Having in gitlab-ci a job like the following one:

static_test_service:
  stage: test code
  script:
    - docker run --rm -v $(pwd):/data -w /data dparra0007/sonar-scanner:20171010-1 sonar-scanner
     -Dsonar.projectKey=$CI_PROJECT_NAMESPACE:$CI_PROJECT_NAME 
     -Dsonar.projectName=$CI_PROJECT_NAME 
     -Dsonar.branch=$CI_COMMIT_REF_NAME 
     -Dsonar.projectVersion=$CI_JOB_ID 
     -Dsonar.sources=./greetingapi/src 
     -Dsonar.java.binaries=./greetingapi/target 
     -Dsonar.gitlab.project_id=$CI_PROJECT_ID 
     -Dsonar.gitlab.commit_sha=$CI_COMMIT_SHA 
     -Dsonar.gitlab.ref_name=$CI_COMMIT_REF_NAME

I would need to fail the gitlab job when the sonarqube analysis fails. But in that case, the error in analysis is reported but not sending a fail status to the job in Gitlab CI and the step always finish with success.

It seems that there is no way to raise any event from "docker run" to be managed by gitlab job.

Any idea on how to force to fail the job if the sonarqube analysis fails?

Thanks,

Upvotes: 2

Views: 2626

Answers (2)

Sanjay Bharwani
Sanjay Bharwani

Reputation: 4799

I faced this problem with GitLab and Sonar where Sonar was failing the QualityAnalysis but GitLab job was still passing with

INFO: ANALYSIS SUCCESSFUL, you can find the results at:

Now the problem is below missing config in sonar.properties

sonar.qualitygate.wait=true
sonar.qualitygate.timeout=1800

So basically, the SonarScan takes time to do the analysis and by default it won't wait for the analysis to complete and may returns default SUCCESSFUL ANALYSIS result to GitLab

With the mentioned configuration, we are explicitly asking GitLab to wait for the qualitygate to finish and gave some timeout as well (in case analysis takes long time to finish)

Now we see the GitLab job fails with below

ERROR: QUALITY GATE STATUS: FAILED - View details 

Upvotes: 3

Sahit
Sahit

Reputation: 520

To break the CI build for a failed Quality Gate, you have write script based on the following steps

1.Search in /report-task.txt the values of the CE Task URL (ceTaskUrl) and CE Task Id (ceTaskId)

2.Call /api/ce/task?id=XXX where XXX is the CE Task Id retrieved from step 1 Ex:- https://yourSonarURL/api/ce/task?id=Your ceTaskId

3.Wait for sometime until the status is SUCCESS, CANCELED or FAILED from Step 2

4.If it is FAILED, break the build (Here failure is unable to generate sonar report)

5.If successful,then Use the analysisId from the JSON returned by /api/ce/task? id=XXX(step2)and Immediately call /api/qualitygates/project_status?analysisId=YYY to check the status of the quality gate. Ex:- https://yourSonarURL/api/qualitygates/project_status?analysisId=Your analysisId

6.Step 5 gives the status of the critical, major and minor error threshold limit

7.Based on the limit break the build.

Upvotes: 1

Related Questions