Integrating SonarQube into GitLab CI
How to use SonarScanner CLI.
This is an example of how you can use the SonarScanner CLI. For example, if you want to scan a PHP application. There are also alternatives: Gradle & Maven.
Create a file called sonar-project.properties
inside of your repository root. As stated in the SonarQube GitLab CI documentation.
# SonarQube server
# sonar.host.url & sonar.login are set by the Scanner CLI.
# See https://docs.sonarqube.org/latest/analysis/gitlab-cicd/.
# Project settings.
sonar.projectKey=my-project
sonar.projectName=My project
sonar.projectDescription=My new interesting project.
sonar.links.ci=https://gitlab.com/my-account/my-project/pipelines
sonar.links.issue=https://jira.example.com/projects/MYPROJECT
# Scan settings.
sonar.projectBaseDir=.
# Define the directories that should be scanned. Comma separated.
sonar.sources=./src,./resources,./web
sonar.test.inclusions=**/*Test.php
sonar.php.coverage.reportPaths=./coverage/lcov.info
sonar.php.file.suffixes=php
sonar.sourceEncoding=UTF-8
sonar.exclusions=,**/coverage/**
# Fail CI pipeline if Sonar fails.
sonar.qualitygate.wait=true
Add a SonarQube stage to your*gitlab-ci.yml
file. I configured it to only run on the Git master
branch. Because I’m using the SonarQube CommunityEdition — which only supports analyzing one branch per repository.*
stages:
- analyze
analyze:sonar:
stage: analyze
image:
name: sonarsource/sonar-scanner-cli:4.5
entrypoint: [""]
variables:
# Defines the location of the analysis task cache
SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"
# Shallow cloning needs to be disabled.
# See https://docs.sonarqube.org/latest/analysis/gitlab-cicd/.
GIT_DEPTH: 0
cache:
key: "${CI_JOB_NAME}"
paths:
- .sonar/cache
script:
- sonar-scanner
rules:
# SonarQube CommunityEdition only supports analyzing a single branch.
# So only run on master.
- if: '$CI_COMMIT_BRANCH == "master"'
when: on_success
- when: never
Add the following variables via the GitLab CI UI. Keep in mind not to commit any credentials to your Git repository.
Go to Settings > CI / CD
Expand Variables
Setting GitLab CI variables
Add the required Sonar variables:
SONAR_HOST_URL
:
SONAR_HOST_URL configuration
SONAR_TOKEN
:
First off, we need a token. To get one, log into you Sonar instance and create a new one:
Go to My Account
Click the Security tab
Enter a token name, and click Generate
Copy the generated token
SONAR_TOKEN configuration
Now your project will show up in SonarQube after the first GitLab CI pipeline run.