Search code examples
jenkinssonarqubejenkins-pipelinebitbucket

How to block Pull Request merges if SonarQube has errors?


We already have plugins installed for the bitbucket server and sonarqube in Jenkins and We ran the sonar using this command in the Jenkinsfile

I also followed this community topic:

agent {
                docker {
                image 'sonar-scanner-cli:4'
                reuseNode true
                }
            }
            steps {
                sh "/usr/bin/entrypoint.sh sonar-scanner -Dsonar.login='<token>' -Dsonar.language=js  -Dsonar.projectKey=<project-key> -Dsonar.sources=test -Dsonar.profile=node -Dsonar.host.url=https://<sonarqube-url> -Dsonar.branch.name=<git-branch-name>" 
            }

SonarQube Version: 8.8

I added the key com.sonarsource.sonarqube in the bitbucket repo > pull requests > code insights but I am getting the error as mentioned in this doc

There is 1 issue preventing you from merging this pull request. Report with key ‘com.sonarsource.sonarqube’ has not yet been created


Solution

  • It's hard to provide an answer that addresses your specific issues, as you haven't provided much information. However, I can give you some background on how this is typically done.

    Concerning what you've provided, you cite a document about decorating pull requests, which has a lot of information. It's not clear at all which error you are referring to.

    The way you use SonarQube and Jenkins to block the merging of pull requests if SonarQube has "errors", is with the Quality Gate, and the configuration of the BitBucket repository.

    You define the SonarQube quality gate with rules for when the scan is to be defined as "failing". For instance, you can define a minimum percentage of unit test code coverage, or the maximum number of vulnerabilities, or other issue types.

    In Jenkins, you need to use the "withSonarQubeEnv()" and "waitForQualityGate()" pipeline steps. The former specifies the name of the SonarQube instance to use, which extracts the SonarQube credentials and url from the Jenkins configuration (you should define them in the Jenkins configuration, not in the build job, as you have done). The latter waits for SonarQube to produce the quality gate analysis, which is performed in a background job in SonarQube. When the background job completes, it will call the "Webhook", the url of which has to be configured in SonarQube, to point to Jenkins (often something like "http://{jenkinshost}:{jenkinsport}/jenkins/sonarqube-webhook"). In the Jenkins pipeline script, you check the return value from "waitForQualityGate()", and if the "status" property of that object is not equal to "OK", then the quality gate failed, and your script should call "error" to fail the build.