Integrating SonarQube Code Scanning with GitLab Commit Status
This guide explains how to set up SonarQube and Sonar‑scanner for static code analysis, run the scanner with project parameters, install the Sonar‑GitLab plugin, configure commit‑status integration, and use the resulting GitLab commit status to enforce merge‑request policies based on pipeline outcomes.
First, install a SonarQube server and download the Sonar‑scanner from the official documentation.
Run the scanner with the following command (replace placeholders with your project details):
sonar-scanner \
-Dsonar.projectKey=microservicecicd-demo-service \
-Dsonar.projectName=microservicecicd-demo-service \
-Dsonar.projectVersion=1.1.1 \
-Dsonar.ws.timeout=30 \
-Dsonar.projectDescription="xxxxxxx" \
-Dsonar.links.homepage=http://www.baidu.com \
-Dsonar.sources=src \
-Dsonar.sourceEncoding=UTF-8 \
-Dsonar.java.binaries=target/classes \
-Dsonar.java.test.binaries=target/test-classes \
-Dsonar.java.surefire.report=target/surefire-reports \
-Dsonar.host.url="http://sonar.idevops.site" \
-Dsonar.login=7c7b5f890dcb3c0ddf6d187fe47a8482f3430c74 \The scan results are displayed in SonarQube, as shown in the screenshot.
To associate scan results with GitLab commits, install the sonar‑gitlab‑plugin (e.g., version 4.1.0‑SNAPSHOT), place the JAR in SonarQube’s extensions directory, grant execution permission, and restart SonarQube.
Configure the plugin by adding the following parameters to the scanner command:
-Dsonar.gitlab.commit_sha=d0f7c74a058df8e935f1e247a68ac23d7d864295 \
-Dsonar.gitlab.ref_name=master \
-Dsonar.gitlab.project_id=39 \
-Dsonar.dynamicAnalysis=reuseReports \
-Dsonar.gitlab.failure_notification_mode=commit-status \
-Dsonar.gitlab.url=http://gitlab.idevops.site \
-Dsonar.gitlab.user_token=ABtkz-f_zkyRXAMeBZSc \
-Dsonar.gitlab.api_version=v4Key parameters:
commit_sha – GitLab commit ID
ref_name – branch name
project_id – GitLab project ID
dynamicAnalysis – fixed value reuseReports
After scanning, SonarQube updates the commit status in GitLab (e.g., success or failure), which can be used to enforce merge‑request policies that require a passing pipeline.
Images illustrate the scanner output and the updated commit status.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.