> For the complete documentation index, see [llms.txt](https://docs.sonarsource.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sonarsource.com/sonarqube-server/8.9/alm-integration/gitlab-integration.md).

# GitLab integration

SonarQube Server 8.9 integrates with GitLab Self-Managed and GitLab.com to maintain code quality and security in your GitLab projects.

{% hint style="info" %}
**For AI agents:** You're in the SonarQube Server 8.9 documentation. For a list of all 8.9 pages, see the [SonarQube Server 8.9 page index](https://4108688904-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FG0n8jfxwZN8LmyH08dMa%2Fuploads%2F8WN59Z2YOHCj6T8O2i2L%2Fsonarqube-server-8.9-llms.txt?alt=media). For the whole site, see the [page index](https://docs.sonarsource.com/llms.txt) or the [full text](https://docs.sonarsource.com/llms-full.txt). For another version, replace 8.9 in the URL with that version. The [latest version](https://docs.sonarsource.com/sonarqube-server/) has no version number in its URL.
{% endhint %}

SonarQube Server’s integration with GitLab Self-Managed and GitLab.com allows you to maintain code quality and security in your GitLab projects.

With this integration, you’ll be able to:

* **Authenticate with GitLab**: Sign in to SonarQube Server with your GitLab credentials.
* **Import your GitLab projects**: Import your GitLab Projects into SonarQube Server to easily set up SonarQube Server projects.
* **Analyze projects with GitLab CI/CD**: Integrate analysis into your build pipeline. Starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), SonarScanners running in GitLab CI/CD jobs can automatically detect branches or merge requests being built so you don’t need to specifically pass them as parameters to the scanner.
* **Add merge request decoration**: (starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/)) See your [Quality gates](/sonarqube-server/8.9/user-guide/quality-gates.md) and code metric results right in GitLab so you know if it’s safe to merge your changes.

## Prerequisites <a href="#gitlab-integration-prerequisites" id="gitlab-integration-prerequisites"></a>

Integration with GitLab self-managed subscriptions requires at least GitLab version 11.7.

### Branch analysis <a href="#branch-analysis" id="branch-analysis"></a>

SonarQube Community Build doesn’t support the analysis of multiple branches, so you can only analyze your main branch. Starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), you can analyze multiple branches and merge requests.

## Authenticating with GitLab <a href="#gitlab-integration-authentication" id="gitlab-integration-authentication"></a>

You can delegate authentication to GitLab using a dedicated GitLab OAuth application.

### Creating a GitLab OAuth app <a href="#creating-a-gitlab-oauth-app" id="creating-a-gitlab-oauth-app"></a>

You can find general instructions for creating a GitLab OAuth app [here](https://docs.gitlab.com/ee/integration/oauth_provider.html).

Specify the following settings in your OAuth app:

* **Name**: your app’s name, such as SonarQube Server.
* **Redirect URI**: enter your SonarQube Server URL with the path `/oauth2/callback/gitlab`. For example, `https://sonarqube.mycompany.com/oauth2/callback/gitlab`.
* **Scopes**: select **api** if you plan to enable group synchronization. Select **read\_user** if you only plan to delegate authentication.

After saving your application, GitLab takes you to the app’s page. Here you find your **Application ID** and **Secret**. Keep these handy, open your SonarQube Server instance, and navigate to **Administration** > **Configuration** > **General Settings** > **ALM Integrations** > **GitLab** > **Authentication**. Set the following settings to finish setting up GitLab authentication:

* **Enabled**: set to `true`.
* **Application ID**: the Application ID is found on your GitLab app’s page.
* **Secret**: the Secret is found on your GitLab app’s page.

On the login form, the new "Log in with GitLab" button allows users to connect with their GitLab accounts.

### GitLab group synchronization <a href="#gitlab-group-synchronization" id="gitlab-group-synchronization"></a>

Enable **Synchronize user groups** at **Administration** > **Configuration** > **General Settings** > **ALM Integrations** > **GitLab** to associate GitLab groups with existing SonarQube Server groups of the same name. GitLab users inherit membership to subgroups from parent groups.

To synchronize a GitLab group or subgroup with a SonarQube Server group, name the SonarQube Server group with the full path of the GitLab group or subgroup URL.

For example, with the following GitLab group setup:

* GitLab group = My Group
* GitLab subgroup = My Subgroup
* GitLab subgroup URL = `https://YourGitLabURL.com/my-group/my-subgroup`

You should name your SonarQube Server group `my-group` to synchronize it with your GitLab group and `my-group/my-subgroup` to synchronize it with your GitLab subgroup.

## Importing your GitLab projects into SonarQube Server <a href="#gitlab-integration-importing-projects" id="gitlab-integration-importing-projects"></a>

Setting up the import of GitLab projects into SonarQube Server allows you to easily create SonarQube Server projects from your GitLab projects. If you’re using [Developer Edition](https://redirect.sonarsource.com/editions/developer.html) or above, this is also the first step in adding merge request decoration.

To set up the import of GitLab projects:

1. Set your global settings
2. Add a personal access token for importing repositories

### Setting your global settings <a href="#setting-your-global-settings" id="setting-your-global-settings"></a>

To import your GitLab projects into SonarQube Server, you need to first set your global SonarQube Server settings. Navigate to **Administration** > **Configuration** > **General Settings** > **ALM Integrations**, select the **GitLab** tab, and specify the following settings:

* **Configuration Name** (Enterprise and Data Center Edition only): The name used to identify your GitLab configuration at the project level. Use something succinct and easily recognizable.
* **GitLab URL**: The GitLab API URL.
* **Personal Access Token**: A GitLab user account is used to decorate Merge Requests. We recommend using a dedicated GitLab account with at least **Reporter** [permissions](https://docs.gitlab.com/ee/user/permissions.html) (the account needs permission to leave comments). Use a personal access token from this account with the **api** scope authorized for the repositories you’re analyzing. This personal access token is used to report your quality gate status to your merge requests. You’ll be asked for another personal access token for importing projects in the following section.

### Adding a personal access token for importing projects <a href="#adding-a-personal-access-token-for-importing-projects" id="adding-a-personal-access-token-for-importing-projects"></a>

After setting these global settings, you can add a project from GitLab by clicking the **Add project** button in the upper-right corner of the **Projects** homepage and selecting **GitLab**.

Then, you’ll be asked to provide a personal access token with `read_api` scope so SonarQube Server can access and list your GitLab projects. This token will be stored in SonarQube Server and can be revoked at any time in GitLab.

After saving your personal access token, you’ll see a list of your GitLab projects that you can **set up** to add to SonarQube Server. Setting up your projects this way also sets your project settings for merge request decoration.

For information on analyzing your projects with GitLab CI/CD, see the following section.

## Analyzing projects with GitLab CI/CD <a href="#analyzing-projects-with-gitlab-ci-cd" id="analyzing-projects-with-gitlab-ci-cd"></a>

SonarScanners running in GitLab CI/CD jobs can automatically detect branches or merge requests being built so you don’t need to specifically pass them as parameters to the scanner.

To analyze your projects with GitLab CI/CD, you need to:

* Set your environment variables.
* Configure your gilab-ci.yml file.

The following sections detail these steps.

{% hint style="warning" %}
You need to disable git shallow clone to make sure the scanner has access to all of your history when running analysis with GitLab CI/CD. For more information, see [**Git shallow clone**](https://docs.gitlab.com/ee/ci/pipelines/settings.html#limit-the-number-of-changes-fetched-during-clone).
{% endhint %}

### Setting environment variables <a href="#setting-environment-variables" id="setting-environment-variables"></a>

You can set environment variables securely for all pipelines in GitLab’s settings. See GitLab’s documentation on [CI/CD variables](https://docs.gitlab.com/ee/ci/variables/#creating-a-custom-environment-variable) for more information.

You need to set the following environment variables in GitLab for analysis:

* **Sonar Token**: Generate a SonarQube Server [Generating and using tokens](/sonarqube-server/8.9/user-guide/user-account/generating-and-using-tokens.md) for GitLab and create a custom environment variable in GitLab with `SONAR_TOKEN` as the **Key** and the token you generated as the **Value**.
* **Sonar Host URL**: Create a custom environment variable with `SONAR_HOST_URL` as the **Key** and your SonarQube Server URL as the **Value**.

### Configuring your gitlab-ci.yml file <a href="#configuring-your-gitlabciyml-file" id="configuring-your-gitlabciyml-file"></a>

This section shows you how to configure your GitLab CI/CD `gitlab-ci.yml` file. The `allow_failure` parameter in the examples allows a job to fail without impacting the rest of the CI suite.

You’ll set up your build according to your SonarQube Server edition:

* **SonarQube Community Build**: SonarQube Community Build doesn’t support multiple branches, so you should only analyze your main branch. You can restrict the analysis to your main branch by adding the branch name to the `only` parameter in your .yml file.
* **Developer Edition and above:** By default, GitLab will build all branches but not merge requests. To build merge requests, you need to update the `.gitlab-ci.yml` file by adding `merge_requests` to the `only` parameter in your .yml. See the example configurations below for more information.

Select the scanner you’re using below to expand an example configuration:

<details>

<summary>SonarScanner for Gradle</summary>

```css-79elbk
sonarqube-check:
  image: gradle:jre11-slim
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"  # Defines the location of the analysis task cache
    GIT_DEPTH: "0"  # Tells git to fetch all the branches of the project, required by the analysis task
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script: gradle sonarqube -Dsonar.qualitygate.wait=true
  allow_failure: true
  only:
    - merge_requests
    - master
    - develop
```

</details>

<details>

<summary>SonarScanner for Maven</summary>

```css-79elbk
sonarqube-check:
  image: maven:3.6.3-jdk-11
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"  # Defines the location of the analysis task cache
    GIT_DEPTH: "0"  # Tells git to fetch all the branches of the project, required by the analysis task
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script:
    - mvn verify sonar:sonar -Dsonar.qualitygate.wait=true
  allow_failure: true
  only:
    - merge_requests
    - master
    - develop
```

</details>

<details>

<summary>SonarScanner CLI</summary>

```css-79elbk
sonarqube-check:
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: [""]
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"  # Defines the location of the analysis task cache
    GIT_DEPTH: "0"  # Tells git to fetch all the branches of the project, required by the analysis task
  cache:
    key: "${CI_JOB_NAME}"
    paths:
      - .sonar/cache
  script:
    - sonar-scanner -Dsonar.qualitygate.wait=true
  allow_failure: true
  only:
    - merge_requests
    - master
    - develop
```

**Project key**\
A project key has to be provided through `sonar-project.properties` or through the command line parameter. For more information, see the [SonarScanner](/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner.md) documentation.

**Self-signed certificates**\
If you secure your SonarQube Server instance with a self-signed certificate, you may need to build a custom image based on `sonarsource/sonar-scanner-cli`. See the section **Advanced docker configuration** within the [SonarScanner](/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner.md) documentation.

</details>

### Failing the pipeline job when the quality gate fails <a href="#failing-the-pipeline-job-when-the-quality-gate-fails" id="failing-the-pipeline-job-when-the-quality-gate-fails"></a>

In order for the quality gate to fail on the GitLab side when it fails on the SonarQube Server side, the scanner needs to wait for the SonarQube Server quality gate status. To enable this, set the `sonar.qualitygate.wait=true` parameter in the `.gitlab-ci.yml` file.

You can set the `sonar.qualitygate.timeout` property to an amount of time (in seconds) that the scanner should wait for a report to be processed. The default is 300 seconds.

### For more information <a href="#for-more-information" id="for-more-information"></a>

For more information on configuring your build with GitLab CI/CD, see the [GitLab CI/CD pipeline configuration reference](https://docs.gitlab.com/ci/yaml/).

## Adding merge request decoration to GitLab <a href="#adding-merge-request-decoration-to-gitlab" id="adding-merge-request-decoration-to-gitlab"></a>

Merge request decoration shows your Quality Gate and analysis metrics directly in GitLab.

After you’ve set up SonarQube Server to import your GitLab projects as shown in the previous section, the simplest way to add merge request decoration is by adding a project from GitLab by clicking the **Add project** button in the upper-right corner of the **Projects** homepage and selecting **GitLab**.

Then, follow the steps in SonarQube Server to analyze your project. The project settings for merge request decoration are set automatically.

{% hint style="info" %}
To decorate merge requests, a SonarQube Server analysis needs to be run on your code. You can find the additional parameters required for merge request analysis on the [Pull request analysis](/sonarqube-server/8.9/analyzing-source-code/pull-request-analysis.md) page.
{% endhint %}

### Adding merge request decoration to a manually created or existing project <a href="#adding-merge-request-decoration-to-a-manually-created-or-existing-project" id="adding-merge-request-decoration-to-a-manually-created-or-existing-project"></a>

To add merge request decoration to a manually created or existing project, make sure your global ALM Integration settings are set as shown in the **Importing your GitLab projects into SonarQube Server** section above, and set the following project settings at **Project Settings** > **General Settings** > **Pull Request Decoration**:

* **Configuration name**: The configuration name that corresponds to your GitLab instance.
* **Project ID**: your GitLab Project ID found in GitLab

### Advanced merge request decoration configuration <a href="#advanced-merge-request-decoration-configuration" id="advanced-merge-request-decoration-configuration"></a>

<details>

<summary>Adding merge request decoration to projects that are part of a mono repository</summary>

*Pull request decoration for a mono repository setup is supported starting in* [*Enterprise Edition*](https://www.sonarsource.com/plans-and-pricing/enterprise/)*.*

In a mono repository setup, multiple SonarQube Server projects, each corresponding to a separate project within the mono repository, are all bound to the same GitLab repository. You’ll need to set up merge request decoration for each SonarQube Server project that is part of a mono repository.

To add merge request decoration to a project that’s part of a mono repository, set your project up manually as shown in the **Adding merge request decoration to a manually created or existing project** section above. You also need to set the **Enable mono repository support** setting to true at **Project Settings** > **General Settings** > **Pull Request Decoration**.

After setting your project settings, you need to ensure the correct project is being analyzed by adjusting the analysis scope and pass your project names to the scanner. See the following sections for more information.

**Ensuring the correct project is analyzed**

You need to adjust the analysis scope to make sure SonarQube Server doesn’t analyze code from other projects in your mono repository. To do this set up a **Source File Inclusion** for your project at **Project Settings > Analysis Scope** with a pattern that will only include files from the appropriate folder. For example, adding `./MyFolderName/**/*` to your inclusions would only include an analysis of code in the `MyFolderName` folder. See [Narrowing the focus](/sonarqube-server/8.9/project-administration/narrowing-the-focus.md) for more information on setting your analysis scope.

**Passing project names to the scanner**

Because of the nature of a mono repository, SonarQube Server scanners might read all project names of your mono repository as identical. To avoid having multiple projects with the same name, you need to pass the `sonar.projectName` parameter to the scanner. For example, if you’re using the Maven scanner, you would pass `mvn sonar:sonar -Dsonar.projectName=YourProjectName`.

</details>

<details>

<summary>Configuring multiple ALM instances</summary>

You can decorate merge requests from multiple ALM instances by creating a configuration for each ALM instance and then assigning that instance configuration to the appropriate projects.

* As part of [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/), you can create one configuration for each ALM.
* Starting in [Enterprise Edition](https://www.sonarsource.com/plans-and-pricing/enterprise/), you can create multiple configurations for each ALM. If you have multiple configurations of the same ALM connected to SonarQube Server, you have to create projects manually.

</details>

<details>

<summary>Linking issues</summary>

During merge request decoration, individual issues will be linked to their SonarQube Server counterparts automatically. For this to work correctly, you need to set the instance’s **Server base URL** (**Administration** > **Configuration** > **General Settings** > **General** > **General**) correctly. Otherwise, the links will default to `localhost`.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.sonarsource.com/sonarqube-server/8.9/alm-integration/gitlab-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
