SonarQube

What is SonarQube.
SonarQube is an open-source platform developed by SonarSource for continuous inspection of code quality. Sonar does static code analysis, which provides a detailed report of bugs, code smells, vulnerabilities, code duplications, This plugin lets you centralize the configuration of SonarQube server connection details in Jenkins global configuration. Then you can trigger SonarQube analysis from Jenkins using standard Jenkins Build Steps or Jenkins Pipeline DSL to trigger analysis with SonarScanner. SonarQube empowers all developers to write cleaner and safer code.

Code coverage, also called test coverage, is a measure of how much of the application’s code has been run in testing. Essentially, it’s a metric that many teams use to check the quality of their tests because it represents the percentage of the production code that has been tested and run. This gives development teams reassurance that their programs have been broadly tested for bugs and should be relatively error-free.

By Mr. Anselem

GitHub Integration
SonarQube’s integration with GitHub Enterprise and GitHub.com allows you to maintain code quality and security in your GitHub repositories.

With this integration, you’ll be able to:

Import your GitHub repositories – Import your GitHub repositories into SonarQube to easily set up SonarQube projects.
Analyze projects with GitHub Actions – Integrate analysis into your build pipeline. Starting in Developer Edition, SonarScanners running in GitHub Actions jobs can automatically detect branches or pull requests being built so you don’t need to specifically pass them as parameters to the scanner.
Report your Quality Gate status to your branches and pull requests – (starting in Developer Edition) See your Quality Gate and code metric results right in GitHub so you know if it’s safe to merge your changes.
Authenticate with GitHub – Sign in to SonarQube with your GitHub credentials.
Prerequisites
To add pull request decoration to Checks in GitHub Enterprise, you must be running GitHub Enterprise version 2.21+.
To analyze projects with GitHub Actions in GitHub Enterprise, you must be running GitHub Enterprise version 3.0+.
Branch Analysis
Community Edition doesn’t support the analysis of multiple branches, so you can only analyze your main branch. With Developer Edition, you can analyze multiple branches and pull requests. Importing your GitHub repositories to SonarQube. You need to use a GitHub App to connect SonarQube and GitHub so you can import your GitHub repositories into SonarQube. This is also the first step in adding authentication, and, starting in Developer Edition, the first step in reporting your analysis and Quality Gate status to your pull requests. If you want to set up authentication without importing your GitHub repositories, see the Creating a dedicated app for authentication section below for instructions on setting up authentication. In this section, you’ll complete the following steps to connect SonarQube and GitHub with a GitHub App:

Create your GitHub App.
Install your GitHub App in your organization.
Update your SonarQube global settings with your GitHub App information.
Step 1: Creating your GitHub App
See GitHub’s documentation on creating a GitHub App for general information on creating your app.

Specify the following settings in your app:

GitHub App Name – Your app’s name.
Homepage URL – You can use any URL, such as https://www.sonarqube.org/.
User authorization callback URL – Your instance’s base URL. For example, https://yourinstance.sonarqube.com.
Webhook URL – Your instance’s base URL. For example, https://yourinstance.sonarqube.com.
Grant access for the following Repository permissions:

Permission                                                                                                        Access             

Checks                                                                                                              Read & write
GitHub Enterprise:  Repository metadata
GitHub.com:  Metadata      (this setting is automatically set by GitHub)        Read-only
Pull Requests                                                                                                    Read & write
Commit statuses                                                                                              Read-only
For private repositories, grant access to the following Repository permissions:

Permission                                                                                                        Access
Contents                                                                                                            Read-only
If setting up GitHub Authentication, in addition to the aforementioned Repository permissions, grant access for the following User permissions:

Permission                                                                                                         Access
Email addresses                                                                                                 Read-only
And grant access for the following Organization permissions:

Permission                                                                                                         Access
Members                                                                                                           Read-only
Projects                                                                                                             Read-only
Under “Where can this GitHub App be installed?,” select Any account.

Step 2: Installing your GitHub App in your organization
Next, you need to install your GitHub App in your organizations. See GitHub’s documentation on installing GitHub Apps for more information.

Step 3: Updating your SonarQube global settings with your GitHub App information
After you’ve created and installed your GitHub App, update your global SonarQube settings to finish integration and allow for the import of GitHub projects.

Navigate to Administration > Configuration > General Settings > DevOps Platform Integrations > GitHub and 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.
  • GitHub URL – For example, https://github.company.com/api/v3 for GitHub Enterprise or https://api.github.com/ for GitHub.com.
  • GitHub App ID – The App ID is found on your GitHub App’s page on GitHub at Settings > Developer Settings > GitHub Apps.
  • Client ID – The Client ID is found on your GitHub App’s page.
  • Client secret – The Client secret is found on your GitHub App’s page. Administrators can encrypt this secret at Administration > Configuration > Encryption. See the Settings Encryption section of the Security page for more information.
  • Private Key – Your GitHub App’s private key. You can generate a .pem file from your GitHub App’s page under Private keys. Copy and paste the whole contents of the file here. Administrators can encrypt this key at Administration > Configuration > Encryption. See the Settings Encryption section of the Security page for more information.

Analyzing projects with GitHub Actions

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

To analyze your projects with GitHub Actions, you need to:

  • Create your GitHub Secrets.
  • Configure your workflow YAML file.
  • Commit and push your code to start the analysis.
  • Creating your GitHub Secrets
  • You can create repository secrets from your GitHub repository. See GitHub’s documentation on Encrypted secrets for more information.

You need to set the following GitHub repository secrets to analyze your projects with GitHub Actions:

SONAR_TOKEN – Generate a SonarQube token and, in GitHub, create a new repository secret in GitHub with SONAR_TOKEN as the Name and the token you generated as the Value.
SONAR_HOST_URL – In GitHub, create a new repository secret with SONAR_HOST_URL as the Name and your SonarQube server URL as the Value.
Configuring your .github/workflows/build.yml file
This section shows you how to configure your .github/workflows/build.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 on.push.branches configuration in your workflow YAML file, and not using on.pull_request.

Developer Edition and above – 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.

The workflow YAML file will usually look something like this:

on:
  # Trigger analysis when pushing in master or pull requests, and when creating
  # a pull request. 
  push:
    branches:
      - master
  pull_request:
      types: [opened, synchronize, reopened]

name: Main Workflow
jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
      with:
        # Disabling shallow clone is recommended for improving relevancy of reporting
        fetch-depth: 0
    - name: SonarQube Scan
      uses: sonarsource/sonarqube-scan-action@master
      env:
        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
====================================================================================
If your source code file names contain special characters that are not covered by the locale range of en_US.UTF-8, you can configure your desired locale like this:

- name: SonarQube Scan
      uses: sonarsource/sonarqube-scan-action@master
      env:
        SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        LC_ALL: "ru_RU.UTF-8"
====================================================================================
You can change the analysis base directory by using the optional input projectBaseDir like this:

- name: SonarQube Scan
  uses: sonarsource/sonarqube-scan-action@master
  with:
    projectBaseDir: app/src
====================================================================================
In case you need to add additional analysis parameters, and you do not wish to set them in the sonar-project.properties file, you can use the args option:

- name: SonarQube Scan
  uses: sonarsource/sonarqube-scan-action@master
  with:
    projectBaseDir: app/src
    args: >
      -Dsonar.python.coverage.reportPaths=coverage.xml
      -Dsonar.tests=tests/
      -Dsonar.verbose=true
====================================================================================

Environment variables
SONAR_TOKEN – Required this is the token used to authenticate access to SonarQube. You can read more about security tokens here. You can set the SONAR_TOKEN environment variable in the "Secrets" settings page of your repository, or you can add them at the level of your GitHub organization (recommended).
SONAR_HOST_URL – Required this tells the scanner where SonarQube is hosted. You can set the SONAR_HOST_URL environment variable in the "Secrets" settings page of your repository, or you can add them at the level of your GitHub organization (recommended).

SonarQube inspects and evaluates everything that affects our codebase, from minor styling details to critical design errors. This enables developers to access and track code analysis data ranging from styling errors, potential bugs and code defects, to design inefficiencies, code duplication, lack of test coverage and excess complexity. It also defines a quality gate, which is a set of measure-based Boolean conditions. Additionally, SonarQube provide an overview of the overall health of the source code by finding code duplications, bugs and other issues in the code. This helps us to know whether our code is production-ready or not.

The complete source code for the article is available. 
Follow by Email
LinkedIn
Share
WhatsApp

New Report

Close