Search code examples
javamavengitlabsonarqube

SonarQube maven plugin - separating build and analysis in CI pipeline


I am setting up a Gitlab CI/CD pipeline for a Java 8 project and need to include a stage for SonarQube analysis. The project is built using Maven. Here is an abbreviated and anonymized version of the job I've defined in the pipeline so far:

sonarqube-check:
  stage: analyze
  image: maven:3.6.3-jdk-11
  variables:
    #
  script: 
    - mvn verify sonar:sonar -Dsonar.projectKey=myproject -Dsonar.java.source=1.8
  allow_failure: true

This fails, because the version of SonarQube we are using requires Java 11, and not all of the relevant jars for a Java 8 project are included by default.

According to the last comment on this thread: sonar.java.jdkHome property does not solve, the sonar step depends on the compilation steps, but it should be possible to run the SonarQube analysis without the build phase, and instead rely on the build artifacts created in an earlier pipeline stage.

Is there a way to exclude the build phase from the maven command line, or somehow build with a different version of Java than is used to run the analysis?


Solution

  • Yes, you can do that by passing artifacts between jobs and directly ask maven to run the Sonarqube plugin.

    In abbreviated, something like that should do it :

    maven-verify:
      stage: build
      image: maven-jdk8-image # Use your jdk8 image
      script:
         - mvn verify
      artifacts:
        paths: 
          - target/
        expire_in: 1 hrs
    
    sonarqube-check:
      stage: analyze
      image: maven:3.6.3-jdk-11
      script: 
          # Set the sonar.java.binaries properties and don't add maven step like verify
        - mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.10.0.2594:sonar -Dsonar.qualitygate.wait=true -Dsonar.java.binaries=target/classes -Dsonar.java.source=1.8
      allow_failure: true