# Bitbucket Cloud integration

SonarQube’s integration with Bitbucket Cloud allows you to maintain code quality and security in your Bitbucket Cloud repositories.

With this integration, you’ll be able to:

* **Analyze projects with Bitbucket Pipelines** - Integrate analysis into your build pipeline. SonarScanners running in Bitbucket Pipelines can automatically detect branches or pull requests being built so you don’t need to specifically pass them as parameters to the scanner (branch and pull request analysis is available starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/)).
* **Add pull request decoration** - (starting in [Developer Edition](https://www.sonarsource.com/plans-and-pricing/developer/)) See your Quality Gate and code metric results right in Bitbucket Cloud so you know if it’s safe to merge your changes.

## Analyzing projects with Bitbucket Pipelines <a href="#analyzing-projects-with-bitbucket-pipelines" id="analyzing-projects-with-bitbucket-pipelines"></a>

SonarScanners running in Bitbucket Pipelines can automatically detect branches or pull requests being built so you don’t need to specifically pass them as parameters to the scanner.

To analyze your projects with Bitbucket Pipelines, you need to:

* Set your environment variables.
* Configure your `bitbucket-pipelines.yml file`.

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

You can set environment variables securely for all pipelines in Bitbucket Cloud’s settings. See [User-defined variables](https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/#User-defined-variables) for more information.

{% hint style="info" %}
You may need to commit your `bitbucket-pipelines.yml` before being able to set environment variables for pipelines.
{% endhint %}

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

* `SONAR_TOKEN`: Generate a SonarQube [generating-and-using-tokens](https://docs.sonarsource.com/sonarqube-server/8.9/user-guide/user-account/generating-and-using-tokens "mention") for Bitbucket Cloud and create a custom **secured** environment variable in Bitbucket Cloud with `SONAR_TOKEN` as the **Name** and the token you generated as the **Value**.
* `SONAR_HOST_URL`: Create a custom environment variable with `SONAR_HOST_URL` as the **Name** and your SonarQube server URL as the **Value**.

### Configuring your bitbucket-pipelines.yml file <a href="#configuring-your-bitbucketpipelinesyml-file" id="configuring-your-bitbucketpipelinesyml-file"></a>

This section shows you how to configure your `bitbucket-pipelines.yml` file.

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

* **Community Edition**: Community Edition doesn’t support multiple branches, so you should only analyze your main branch. You can restrict analysis to your main branch by setting it as the only branch in your `branches` pipeline in your `bitbucket-pipelines.yml` file and not using the `pull-requests` pipeline.
* **Developer Edition and above**: Bitbucket Pipelines can build specific branches and pull requests if you use the `branches` and `pull-requests` pipelines as shown in the example configurations below.

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

**Note:** This assumes a typical Gitflow workflow. See [Use glob patterns on the Pipelines YAML file](https://support.atlassian.com/bitbucket-cloud/docs/use-glob-patterns-on-the-pipelines-yaml-file/) provided by Atlassian for more information on customizing whi branches or pull requests trigger an analysis.

<details>

<summary>SonarScanner for Gradle</summary>

**Note:** A project key might have to be provided through a `build.gradle` file, or through the command line parameter. For more information, see the [sonarscanner-for-gradle](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner-for-gradle "mention") documentation.

Add the following to your `build.gradle` file:

```css-79elbk
plugins {
  id "org.sonarqube" version "3.1"
}
```

Write the following in your `bitbucket-pipelines.yml`:

```css-79elbk
image: openjdk:8

clone:
  depth: full

pipelines:
  branches:
    '{master,develop}':
      - step:
          name: SonarQube analysis
          caches:
            - gradle
            - sonar
          script:
            - bash ./gradlew sonarqube

  pull-requests:
    '**':
      - step:
          name: SonarQube analysis
          caches:
            - gradle
            - sonar
          script:
            - bash ./gradlew sonarqube

definitions:
  caches:
    sonar: ~/.sonar
```

</details>

<details>

<summary>SonarScanner for Maven</summary>

**Note:** A project key might have to be provided through a `pom.xml` file, or through the command line parameter. For more information, see the [sonarscanner-for-maven](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner-for-maven "mention") documentation.

Write the following in your `bitbucket-pipelines.yml`:

```css-79elbk
image: maven:3.3.9

clone:
  depth: full

pipelines:
  branches:
    '{master,develop}':
      - step:
          name: SonarQube analysis
          caches:
            - maven
            - sonar
          script:
            - mvn verify sonar:sonar

  pull-requests:
    '**':
      - step:
          name: SonarQube analysis
          caches:
            - maven
            - sonar
          script:
            - mvn verify sonar:sonar

definitions:
  caches:
    sonar: ~/.sonar
```

</details>

<details>

<summary>SonarScanner for .NET</summary>

Write the following in your `bitbucket-pipelines.yml`:

```css-79elbk
image: mcr.microsoft.com/dotnet/core/sdk:latest

definitions:
  steps:
    - step: &build-step
        name: SonarQube analysis
        caches:
          - dotnetcore
          - sonar
        script:
          - apt-get update
          - apt-get install --yes openjdk-11-jre
          - dotnet tool install --global dotnet-sonarscanner
          - export PATH="$PATH:/root/.dotnet/tools"
          - dotnet sonarscanner begin /k:"YOUR_PROJECT_KEY*" /d:"sonar.login=${SONAR_TOKEN}"  /d:"sonar.host.url=${SONAR_HOST_URL}"
          - dotnet build 
          - dotnet sonarscanner end /d:"sonar.login=${SONAR_TOKEN}"
  caches:
    sonar: ~/.sonar

clone:
  depth: full

pipelines:
  branches:
    '{master,main,develop}':
      - step: *build-step
  pull-requests:
    '**':
      - step: *build-step
```

</details>

<details>

<summary>SonarScanner CLI</summary>

{% hint style="info" %}
The Advanced Configuration below is an alternative to the SonarQube Scan Bitbucket Pipe. If you do not need a setup that allows for scanner caching, we recommend using the Bitbucket Pipe configuration.
{% endhint %}

**Note:** A project key has to be provided through a `sonar-project.properties` file, or through the command line parameter. For more information, see the [sonarscanner](https://docs.sonarsource.com/sonarqube-server/8.9/analyzing-source-code/scanners/sonarscanner "mention") documentation.

Write the following in your `bitbucket-pipelines.yml`:

```css-79elbk
clone:
  depth: full

pipelines:
  branches:
    '{master,develop}':
      - step:
          name: SonarQube analysis
          image: sonarsource/sonar-scanner-cli:latest
          caches:
            - sonar
          script:
            - sonar-scanner

  pull-requests:
    '**':
      - step:
          name: SonarQube analysis
          image: sonarsource/sonar-scanner-cli:latest
          caches:
            - sonar
          script:
            - sonar-scanner

definitions:
  caches:
    sonar: /opt/sonar-scanner/.sonar
```

</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 the pipeline when it is red on the SonarQube side, the scanner needs to wait for the SonarQube Quality Gate status. To enable this, pass the `-Dsonar.qualitygate.wait=true` parameter to the scanner in the `bitbucket-pipelines.yml` file.

Example:

```css-79elbk
mvn verify sonar:sonar -Dsonar.qualitygate.wait=true
```

This will make the analysis step poll SonarQube regularly until the quality gate is computed. This will increase your pipeline duration. Note that, if the quality gate is red, this will make the analysis step fail, even if the actual analysis itself is successful. We advise only using this parameter when necessary (for example, to block a deployment pipeline if the quality gate is red). It should not be used to report the quality gate status in a pull request, as this is already done with pull request decoration.

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 Bitbucket Pipelines, see the [Configure bitbucket-pipelines.yml](https://support.atlassian.com/bitbucket-cloud/docs/configure-bitbucket-pipelinesyml/) documentation provided by Atlassian.

## Adding pull request decoration to Bitbucket Cloud <a href="#adding-pull-request-decoration-to-bitbucket-cloud" id="adding-pull-request-decoration-to-bitbucket-cloud"></a>

Pull request decoration shows your Quality Gate and analysis metrics directly in Bitbucket Cloud. To set up pull request decoration, you need to do the following:

1. Set up a dedicated OAuth consumer to decorate your pull requests.
2. Set your global **ALM Integration** settings.
3. Set your project-level **Pull Request Decoration** settings.

{% hint style="info" %}
To decorate a pull request, a SonarQube analysis needs to be run on your code. You can find the additional parameters required for pull request analysis on the [bitbucket-cloud-integration](https://docs.sonarsource.com/sonarqube-server/8.9/alm-integration/bitbucket-cloud-integration "mention") page.
{% endhint %}

### Setting up your OAuth consumer <a href="#setting-up-your-oauth-consumer" id="setting-up-your-oauth-consumer"></a>

SonarQube uses a dedicated OAuth consumer to decorate pull requests. You need to create the OAuth consumer in your Bitbucket Cloud workspace settings and specify the following:

* **Name**: The name of your OAuth consumer.
* **Callback URL:** Bitbucket Cloud requires this field, but it’s not used by SonarQube so you can use any URL.
* **This is a private consumer:** Your OAuth consumer needs to be private. Make sure this check box is selected.
* **Permissions**: Grant **Read** access for the **Pull requests** permission.

### Setting your global ALM Integration settings <a href="#setting-your-global-alm-integration-settings" id="setting-your-global-alm-integration-settings"></a>

To set your global ALM Integration settings, navigate to **Administration** > **ALM Integrations**, select the **Bitbucket** tab, and select **Bitbucket Cloud** as the variant you want to configure. From here, specify the following settings:

* **Configuration Name**: (Enterprise and Data Center Edition only) The name used to identify your GitHub configuration at the project level. Use something succinct and easily recognizable.
* **Workspace ID**: The workspace ID is part of your bitbucket cloud URL `https://bitbucket.org/{WORKSPACE-ID}/{repository-slug}`.
* **OAuth Key**: Bitbucket automatically creates an OAuth key when you create your OAuth consumer. You can find it in your Bitbucket Cloud workspace settings under **OAuth consumers**.
* **OAuth Secret**: Bitbucket automatically creates an OAuth secret when you create your OAuth consumer. You can find it in your Bitbucket Cloud workspace settings under **OAuth consumers**.

### Setting your project-level Pull Request Decoration settings <a href="#setting-your-projectlevel-pull-request-decoration-settings" id="setting-your-projectlevel-pull-request-decoration-settings"></a>

From your project **Overview**, navigate to **Project Settings** > **General Settings** > **Pull Request Decoration**.

From here, set your:

* **Configuration name**: The configuration name that corresponds to your Bitbucket Cloud instance.
* **Repository SLUG**: The repository SLUG is part of your bitbucket cloud URL `https://bitbucket.org/{workspace-id}/{REPOSITORY-SLUG}`.

<details>

<summary>Adding pull 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 projects, each corresponding to a separate project within the mono repository, are all bound to the same Bitbucket Cloud repository. You’ll need to set up pull request decoration for each SonarQube project that is part of a mono repository.

To add pull request decoration to a project that’s part of a mono repository, set your project up as shown in the **Adding pull request decoration to Bitbucket Cloud** 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 <a href="#ensuring-the-correct-project-is-analyzed" id="ensuring-the-correct-project-is-analyzed"></a>

You need to adjust the analysis scope to make sure SonarQube 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 analysis of code in the `MyFolderName` folder. See [narrowing-the-focus](https://docs.sonarsource.com/sonarqube-server/8.9/project-administration/narrowing-the-focus "mention") for more information on setting your analysis scope.

#### Passing project names to the scanner <a href="#passing-project-names-to-the-scanner" id="passing-project-names-to-the-scanner"></a>

Because of the nature of a mono repository, SonarQube 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 platform instances</summary>

You can decorate pull 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, you have to create projects manually.

</details>

<details>

<summary>Linking issues</summary>

During pull request decoration, individual issues will be linked to their SonarQube 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>
