# Github Actions

To configure an analysis of your project using GitHub Actions, you will use the SonarQube Scan GitHub Action.

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

From SonarQube Scan GitHub Action version 5.0.0 (`sonarqube-scan-action`):

* 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), you need to ensure that the following utilities are installed and available in the `PATH`: `unzip`, `wget` or `curl`.

## SonarQube Scan GitHub Action update notes

<details>

<summary>in v7, the SonarQube Scan GitHub Action uses Scanner CLI v8</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>In v6, the SonarQube Scan GitHub Action handles arguments differently</summary>

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

</details>

<details>

<summary>In v5, SonarQube Scan GitHub Action is not based on Docker</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:

* issues with analyzers requiring access to a system-level directories, 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 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>

## Analysis setup overview

You should follow the in-product tutorial when creating a new project. When it’s time to **Choose your Analysis Method** during setup, select **With GitHub Actions**. You can also access the tutorials for an existing project by going to *Your Project* > **Administration** > **Analysis Method**.

The tutorial will walk you through the precise steps to set up the analysis but the basic steps are these:

1. Define the `SONAR_TOKEN` environment variable in your repository by setting up a GitHub Secret. The `SONAR_TOKEN` identifies and authenticates you to SonarQube Cloud. The tutorial will provide the precise value for your specific account. To generate the token, see:
   * From the Team plan: [scoped-organization-tokens](https://docs.sonarsource.com/sonarqube-cloud/administering-sonarcloud/managing-organization/scoped-organization-tokens "mention").
   * With the Free plan: [managing-tokens](https://docs.sonarsource.com/sonarqube-cloud/managing-your-account/managing-tokens "mention").
2. Set the parameters used to connect to the instance and identify the project. See:

   * [#server-connection](https://docs.sonarsource.com/sonarqube-cloud/analysis-parameters/parameters-not-settable-in-ui#server-connection "mention")
   * [#project-identification](https://docs.sonarsource.com/sonarqube-cloud/analysis-parameters/parameters-not-settable-in-ui#project-identification "mention")

   The tutorial will be populated with the correct values for your specific account. The parameters are set differently depending on your project type:

   * In the `pom.xml` for Java Maven projects.
   * In the `build.gradle` file for Java Gradle projects.
   * In the SonarScanner command line for .NET projects.
   * In the `sonar-project.properties` file for other types of projects.

   You can also add additional analysis parameters to further specify your analysis details. For more information about analysis parameters setup, see [configuration-overview](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/analysis-parameters/configuration-overview "mention").
3. Set up your workflow file that defines the steps of your build. In addition to the usual steps that build your project, you need to invoke the SonarScanner to perform the analysis of your code. For more information, see below.

## Setting up your workflow file

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

GitHub Actions can build specific branches and pull requests if you use `on.push.branches` and `on.pull-requests` configurations as shown in the examples below.

In the tabs below, click the scanner you’re using to expand the example configuration:

* For Maven projects: SonarScanner for Maven
* For Gradle projects: SonarScanner for Gradle
* For .NET projects: SonarScanner for .NET
* For other projects: SonarScanner CLI

{% hint style="info" %}
In the example configurations, the EU region is used. If you want to use the US region, See [getting-started-in-us-region](https://docs.sonarsource.com/sonarqube-cloud/getting-started/getting-started-in-us-region "mention").
{% endhint %}

{% tabs %}
{% tab title="Maven" %}
Write the following in your workflow YAML file.

{% hint style="info" %}
A project key might have to be provided through the command line parameter. For more information, see [sonarscanner-for-maven](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/scanners/sonarscanner-for-maven "mention").
{% endhint %}

```yml
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 }}
       run: mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar
```

{% endtab %}

{% tab title="Gradle" %}

1. Activate the SonarScanner for Gradle in your build. See [#analyzing](https://docs.sonarsource.com/sonarqube-cloud/scanners/sonarscanner-for-gradle#analyzing "mention").
2. Write the following in your workflow YAML file.

```yml
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 }}
       run: ./gradlew build sonar --info

```

{% endtab %}

{% tab title=".NET" %}
Write the following in your workflow YAML file.

```yml
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 }}"
         dotnet build
         .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"

```

{% endtab %}

{% tab title="CLI" %}
You can easily set up a basic configuration using the[ SonarQube Scan](https://github.com/marketplace/actions/official-sonarqube-scan) GitHub action, for all languages, including C, C++, Objective-C, and Dart.

You’ll find the GitHub Actions and configuration instructions page on the GitHub Marketplace.

For C, C++, and Objective-C projects relying on Build Wrapper to generate the compilation database (see the CFamily [prerequisites](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/languages/c-family/prerequisites "mention") page), use the `sonarqube-scan-action/install-build-wrapper` sub-action to install the Build Wrapper.
{% endtab %}
{% endtabs %}

## Preventing pull request merges when the quality gate fails <a href="#prevent-pull-request-merge" id="prevent-pull-request-merge"></a>

See [#preventing-the-pull-request-merge-if-the-quality-gate-fails](https://docs.sonarsource.com/sonarqube-cloud/managing-your-projects/administering-your-projects/devops-platform-integration/github#preventing-the-pull-request-merge-if-the-quality-gate-fails "mention").

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

You fail a GitHub Actions workflow on quality-gate failure by making the scanner wait for the Quality Gate result and exit non-zero if it’s failed.

To do so, use the `sonar.qualitygate.wait` analysis parameter (optionally with `sonar.qualitygate.timeout`). For more information about these parameters, see [#quality-gate](https://docs.sonarsource.com/sonarqube-cloud/analysis-parameters/parameters-not-settable-in-ui#quality-gate "mention").

## Analyzing Monorepo Projects: Build Configuration <a href="#analyzing-monorepo-projects-build-configuration" id="analyzing-monorepo-projects-build-configuration"></a>

The example below shows how you could set up a yml file for multiple projects in a monorepo. If you want to analyze a monorepo that contains more than one project ensure that you specify the paths to each sub-project for analysis in your build file.

To ensure that your monorepo works as expected, you need to build each project in the monorepo separately with a unique project key for each one.

**GitHub Actions .yml file**

```yaml
name: My Test Monorepo Project
on:
  push:
      branches:
      - main
      paths:
      - 'lambdas/test/**'
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  sonarqubeScan1:
    name: SonarQubeScan1
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  
      - name: SonarQube Scan
        uses: SonarSource/sonarqube-scan-action@v7
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        with:
          projectBaseDir: repo1/
          
  sonarqubeScan2:
    name: SonarQubeScan2
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0  
      - name: SonarQube Scan
        uses: SonarSource/sonarqube-scan-action@v7
        env: 
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        with:
          projectBaseDir: repo2/
```

## Managing certificates for the SonarQube Cloud scan GitHub Action <a href="#certificate-sonarqube-scan-action" id="certificate-sonarqube-scan-action"></a>

If you use the [sonarqube-scan-action](https://github.com/SonarSource/sonarqube-scan-action) for your GitHub Action and SonarQube Cloud is behind a secured proxy with certificates that need to be recognized by the GitHub runner, you’ll need to set the `SONAR_ROOT_CERT` environment variable in GitHub.

## Troubleshooting <a href="#tbs" id="tbs"></a>

### Scanner cannot resolve file paths in test coverage report <a href="#scanner-cannot-resolve-file-paths-in-test-coverage-report" id="scanner-cannot-resolve-file-paths-in-test-coverage-report"></a>

When using GitHub Action, the SonarScanner fails to resolve the paths within the test coverage report and raises the warning "Could not resolve \<n> file paths in \<file>".

You may resolve this problem by switching off `relative_paths=True` in the coverage settings.

### "Container action is only supported on Linux" error <a href="#container-action-is-only-supported-on-linux-error" id="container-action-is-only-supported-on-linux-error"></a>

You may encounter this error if you use the SonarQube Scan GitHub Action before version 4, i.e. `sonarcloud-github-action`. This action is based on Docker and is only supported on Linux runners. In that case, move to `sonarqube-scan-action` (see [#prerequisites](#prerequisites "mention")).

### "Container action is only supported on Linux" error <a href="#container-action-is-only-supported-on-linux-error" id="container-action-is-only-supported-on-linux-error"></a>

You may encounter this error if you use the SonarQube Scan GitHub Action before version 4, i.e. `sonarcloud-github-action`. This action is based on Docker and is only supported on Linux runners. In that case, move to `sonarqube-scan-action` (see *Preqrequisites* above).

### "The job was not started because recent account payments have failed" error

You may encounter this GitHub error if your GitHub options are set to use a GitHub-hosted runner instead of your self-hosted runner. In this case, we recommend checking your GitHub options to ensure your self-hosted runner is selected.

## Related pages

* [getting-started-in-us-region](https://docs.sonarsource.com/sonarqube-cloud/getting-started/getting-started-in-us-region "mention")

## Related online courses

* <i class="fa-desktop">:desktop:</i> [Configuring code analysis for SonarQube Cloud with GitHub Actions](https://www.sonarsource.com/learn/course/sonarqube-cloud/d77cd975-f3c7-4ee9-bda5-9e25447d1c9b/configuring-code-analysis-for-sonarqube-cloud-with-azure-pipelines)
* <i class="fa-desktop">:desktop:</i> [Configuring pull request decoration for SonarQube Cloud with GitHub Actions](https://www.sonarsource.com/learn/course/sonarqube-cloud/2b1101c1-91b5-4a30-a0be-cbcccd8c2a61/configuring-pull-request-decoration-for-sonarqube-cloud-with-github-actions)

  <br>
