# Adding analysis to GitHub Actions workflow

Once you have created your project in SonarQube Community Build, you can add the SonarQube Community Build analysis to your GitHub Actions workflow:

1. Configure the project analysis parameters.
2. Add the analysis to your GitHub Actions workflows.
3. Commit and push your code to start the analysis.

<details>

<summary>Considerations about upgrading to GitHub Action v7</summary>

The SonarQube Scan GitHub Action version 7 uses the Scanner CLI v8. Please see this [release note for the SonarQube Scan GitHub Action](https://github.com/SonarSource/sonarqube-scan-action/releases/tag/v7.0.0).

* The main change on Scanner CLI v8 is related to the embedded JRE version which is now Java 21. Please see [this release note for the SonarScanner CLI](https://github.com/SonarSource/sonar-scanner-cli/releases/tag/8.0.0.6341).

</details>

<details>

<summary>Considerations about upgrading to GitHub Action v6</summary>

When updating to SonarQube Scan GitHub action `v6`, you might have to update your workflow to change how arguments are quoted because the `args` input is parsed differently. See [this release note](https://github.com/SonarSource/sonarqube-scan-action/releases/tag/v6.0.0) for more information.

</details>

<details>

<summary>Considerations about upgrading to GitHub Action v5</summary>

`v3.1.0` and below of the GitHub Action are based on Docker: at every execution of the action, a dedicated docker container is spawned.

The advantage of using container are primarily:

* **Isolation**, since the SonarScanner gets only access to the directory where the project is checked out.
* **Full control of the environment** where the SonarScanner is executed, in terms of required utilities such as `wget` and `keytool`.

The use of Docker comes, however, with multiple disadvantages regarding SonarQube analysis:

* Issues with analyzers requiring access to a system-level directory, such as cache of dependencies in Java or Dart.
* Issues with DockerHub rate limit on peak workload scenarios.
* Requirement by GitHub to run as root user.
* Support for Docker-based actions limited to Linux - no support of Windows nor MacOS.

`v5` doesn't have the Docker dependency, making the action [composite](https://docs.github.com/en/actions/sharing-automations/creating-actions/creating-a-composite-action). The action now runs in the environment of the runner executing the GitHub workflow.

</details>

## Prerequisites <a href="#prerequisites" id="prerequisites"></a>

<details>

<summary>From GitHub Action version v5</summary>

* If your runner is [GitHub-hosted](https://docs.github.com/en/actions/using-github-hosted-runners/using-github-hosted-runners/about-github-hosted-runners), all required utilities should be already provided by default.
* If your runner is [self-hosted](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self-hosted-runners), ensure that the following utilities are installed and available in the `PATH`: `unzip`, `wget` or `curl`.

</details>

<details>

<summary>If your SonarQube uses certificates</summary>

If you use the [sonarqube-scan-action](https://github.com/SonarSource/sonarqube-scan-action) for your GitHub Action and your SonarQube Server has certificates that need to be recognized by the GitHub runner, you’ll need to set the `SONAR_ROOT_CERT` environment variable in GitHub, see [manage-tls-certificates](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/scanner-environment/manage-tls-certificates "mention") for more information.

</details>

## Configuring the project analysis parameters <a href="#analysis-parameters" id="analysis-parameters"></a>

For general information, see [analysis-parameters](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/analysis-parameters "mention") and the respective SonarScanner section: [sonarscanner-for-maven](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/sonarscanner-for-maven "mention"), [sonarscanner-for-gradle](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/sonarscanner-for-gradle "mention"), [using](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/dotnet/using "mention") for .NET, the [sonarscanner](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/sonarscanner "mention"), or the [configuring](https://docs.sonarsource.com/sonarqube-community-build/analyzing-source-code/scanners/npm/configuring "mention") for NPM pages.

The setting of `sonar.token` and `sonar.host.url` is specific to GitHub Actions: With GitHub Actions, you can configure these parameters in GitHub. This may be done at the global level, or at the project level by the Project Administrator as explained below. It makes sense to store the server URL at the global level.

### Storing the authentication token in GitHub for your project <a href="#storing-the-authentication-token-in-github-for-your-project" id="storing-the-authentication-token-in-github-for-your-project"></a>

The authentication token used in GitHub Actions workflows should be securely stored in a GitHub secret: see GitHub’s documentation on [Encrypted secrets](https://docs.github.com/en/actions/reference/encrypted-secrets) for more information.

Proceed as follows

1. In the SonarQube Community Build UI, generate a SonarQube Community Build token for your project.
2. Create a repository secret in GitHub with:
   * Name: SONAR\_TOKEN
   * Value: the token you generated in the previous step.

### Storing the SonarQube Server URL in GitHub for your project <a href="#storing-the-sonarqube-server-url-in-github-for-your-project" id="storing-the-sonarqube-server-url-in-github-for-your-project"></a>

Create an [organization variable](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/store-information-in-variables) in GitHub with:

* Name: SONAR\_HOST\_URL
* Value: SonarQube Server URL

## Configuring the build.yml file <a href="#configure-build-yml" id="configure-build-yml"></a>

This section shows you how to configure your `.github/workflows/build.yml` file.

SonarQube Community Build 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 `on.push.branches` configuration in your workflow YAML file, and not using `on.pull_request`.

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

{% hint style="warning" %}
The errors "*Missing blame information…*" and "*Could not find ref…*" can be caused by checking out with a partial or shallow clone, or when using Git submodules. You should disable git shallow clone to make sure the scanner has access to all of your history when running analysis with GitHub Actions.

For more information, see the [GitHub Actions Checkout README](https://github.com/actions/checkout).
{% endhint %}

<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-community-build/analyzing-source-code/scanners/sonarscanner-for-gradle "mention") documentation.

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

```groovy
plugins {
  id "org.sonarqube" version "<FULL_VERSION_NUMBER>"
}
```

We recommend using the latest version of the scanner.

Write the following in your workflow YAML file:

```yaml
name: Build
on:
  push:
    branches:
      - main # the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Set up JDK 17
        uses: actions/setup-java@v1
        with:
          java-version: 17
      - name: Cache SonarQube packages
        uses: actions/cache@v4
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache Gradle packages
        uses: actions/cache@v4
        with:
          path: ~/.gradle/caches
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
          restore-keys: ${{ runner.os }}-gradle
      - name: Build and analyze
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}
        run: ./gradlew build sonar --info
```

</details>

<details>

<summary>SonarScanner for Maven</summary>

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

Write the following in your workflow YAML file:

```yaml
name: Build
on:
  push:
    branches:
      - main # the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Set up JDK 17
        uses: actions/setup-java@v1
        with:
          java-version: 17
      - name: Cache SonarQube packages
        uses: actions/cache@v4
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache Maven packages
        uses: actions/cache@v4
        with:
          path: ~/.m2
          key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
          restore-keys: ${{ runner.os }}-m2
      - name: Build and analyze
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}
        run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
```

</details>

<details>

<summary>SonarScanner for .NET</summary>

Write the following in your workflow YAML file:

```yaml
name: Build
on:
  push:
    branches:
      - main # the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  build:
    name: Build
    runs-on: windows-latest
    steps:
      - name: Set up JDK 17
        uses: actions/setup-java@v1
        with:
          java-version: 1.17
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: Cache SonarQube packages
        uses: actions/cache@v4
        with:
          path: ~\.sonar\cache
          key: ${{ runner.os }}-sonar
          restore-keys: ${{ runner.os }}-sonar
      - name: Cache SonarQube scanner
        id: cache-sonar-scanner
        uses: actions/cache@v4
        with:
          path: .\.sonar\scanner
          key: ${{ runner.os }}-sonar-scanner
          restore-keys: ${{ runner.os }}-sonar-scanner
      - name: Install SonarQube scanner
        if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'
        shell: powershell
        run: |
          New-Item -Path .\.sonar\scanner -ItemType Directory
          dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner
      - name: Build and analyze
        shell: pwsh
        run: |
          # Fail fast and propagate errors to the runner
          # https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-7.5
          $ErrorActionPreference = "Stop"
          $PSNativeCommandUseErrorActionPreference = $true
          .\.sonar\scanner\dotnet-sonarscanner begin /k:"example" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="${{ vars.SONAR_HOST_URL }}"
          dotnet build
          .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"
```

</details>

<details>

<summary>SonarScanner CLI</summary>

You can easily set up a basic configuration using the [SonarQube Scan](https://github.com/marketplace/actions/official-sonarqube-scan) GitHub action.

</details>

## Failing the workflow when the quality gate fails <a href="#fail-workflow-on-quality-gate-failure" id="fail-workflow-on-quality-gate-failure"></a>

You can use the [SonarQube quality gate check GitHub Action](https://github.com/marketplace/actions/sonarqube-quality-gate-check) to ensure your code meets your quality standards by failing your workflow when your quality gate fails.

If you do not want to use the SonarQube Community Build quality gate Check Action, you can instruct the scanner to wait for the SonarQube Community Build quality gate status at the end of the analysis. To enable this, pass the `-Dsonar.qualitygate.wait=true` parameter to the scanner in the workflow YAML file.

This will make the analysis step poll SonarQube Community Build regularly until the quality gate is computed. This will increase your workflow 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 workflow if the quality gate is red).

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.
