Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

SonarQube Integration with Docker Scout: Ensuring Code Quality for Docker Images

7 min read

SonarQube is a platform for continuous code quality inspection. It helps developers and organizations ensure the quality of their code by automatically analyzing it for various issues, including:

  • Bugs: SonarQube identifies potential bugs in your code before they reach production, helping you avoid costly errors and improve software stability.
  • Code smells: These are patterns that indicate potential problems in your code, even if it doesn’t contain any obvious bugs. Fixing code smells makes your code cleaner, more maintainable, and easier to understand.
  • Security vulnerabilities: SonarQube can scan your code for security weaknesses that could be exploited by attackers. This helps you build secure software and protect your users’ data.
  • Duplication: SonarQube can detect duplicated code across your codebase, which can be a sign of inefficiency and can make your code harder to maintain.
  • Code coverage: SonarQube measures the percentage of your code that is covered by unit tests.

The SonarQube integration enables Docker Scout to surface SonarQube quality gate checks through Policy Evaluation, under a new Quality gates passed policy. 

How it works?

Under the hood, the SonarQube integration:

  • Uses your user token to create a webhook in your SonarQube instance.
  • Listens for whenever a SonarQube analysis is completed to store the quality gate results into the Scout platform.

This integration uses SonarQube webhooks to notify Docker Scout of when a SonarQube project analysis has completed. When the webhook is called, Docker Scout receives the analysis results, and stores them in the database.

When you push a new image to a repository, Docker Scout evaluates the results of the SonarQube analysis record corresponding to the image. Docker Scout uses Git provenance metadata on the images, from provenance attestations or an OCI annotations, to link image repositories with SonarQube analysis results.

An Overview of Quality gates Passes Policy

The “Quality gates passed” policy within the Docker Scout and SonarQube integration serves as a crucial step in ensuring code quality for your Docker images. Here’s a breakdown of its key aspects:

Purpose:

Continuously assess the quality of your source code within Docker images by leveraging SonarQube’s code analysis capabilities.

Functioning:

  1. SonarQube analysis: Your codebase is analyzed by SonarQube against predefined quality gates, which set acceptable thresholds for various metrics like bugs, code smells, and vulnerabilities.
  1. Result ingestion: Docker Scout retrieves the analysis results from SonarQube via the integration.
  1. Image linkage: Docker Scout links the analysis results to specific Docker image versions using Git provenance information (attestations or OCI annotations).
  1. Policy evaluation: When a new image is pushed, Docker Scout evaluates it against the “Quality gates passed” policy. This policy checks if the image’s SonarQube analysis adheres to the quality gates defined in SonarQube.
  1. Outcome:
  • Pass: If the image meets the quality gates, the policy passes, indicating acceptable code quality and potentially allowing deployment or other positive actions.
  • Fail: If the image violates any quality gate thresholds, the policy fails, highlighting potential issues in the code that require attention. This could trigger alerts, block deployment, or initiate remediation workflows.

Benefits:

  • Automated quality checks: Streamlines quality assessment by automatically applying SonarQube analysis results to Docker images.
  • Gatekeeper for deployments: Enforces quality standards by preventing deployment of images with failing code analysis.
  • Early problem detection: Identifies potential code issues early in the development cycle, facilitating faster resolution.
  • Improved security and reliability: Contributes to building secure and reliable software by ensuring code quality compliance.

Who’s this for?

This integration between Docker Scout and SonarQube caters to a diverse audience within the software development ecosystem, particularly those concerned with continuous improvement and quality assurance for their Docker images. Here are some specific groups who might find this integration particularly beneficial:

  1. Developers:
  • Streamlined quality checks: Developers can integrate code quality assessment directly into their CI/CD pipeline, receiving automated feedback from SonarQube within Docker Scout after each push.
  • Early problem detection: The integration helps identify potential code issues early in the development cycle, allowing developers to address them before they reach production.
  • Improved code ownership: Developers can take ownership of code quality within their images, aligning development efforts with established quality standards.
  1. Software engineers and IT operations:
  • Automated quality gate implementation: The “Quality gates passed” policy helps enforce code quality standards by preventing deployment of images with failing SonarQube analysis.
  • Continuous visibility into code quality: The integration provides a consolidated view of code quality alongside image security assessments within Docker Scout, offering comprehensive insights for software engineers and IT operations.
  • Simplified security and compliance: Enforcing quality gates through SonarQube analysis contributes to building secure and compliant software by reducing the risk of vulnerabilities and code flaws reaching production.
  1. DevOps teams:
  • Automated workflows: The integration can be incorporated into existing DevOps workflows, triggering specific actions (e.g., notifications, remediation pipelines) based on the outcome of the SonarQube analysis and policy evaluation.
  • Improved collaboration: By aligning code quality with image security assessments, the integration fosters collaboration between developers and security teams, promoting a shared responsibility for software quality.
  • Reduced release risks: Proactive identification and handling of code issues through the integration minimizes the risk of deploying flawed images, leading to more stable and reliable releases.
  1. Security professionals:
  • Advanced code vulnerability detection: SonarQube’s code analysis goes beyond traditional security scans, uncovering potential vulnerabilities and code weaknesses at the source level.
  • Strengthened security posture: Integrating code quality assessment with Docker image security strengthens the overall security posture of applications and infrastructure.
  • Data-driven security decisions: The detailed analysis data provided by SonarQube informs security decisions and prioritizes remediation efforts effectively.

Overall, this integration caters to a broad range of stakeholders within the software development lifecycle, from individual developers to security professionals and DevOps teams. It empowers them to ensure code quality and security compliance by automating code assessments and integrating them seamlessly into their existing workflows.

Benefits of using Scout with SonarQube

Scout acts as a management layer that leverages SonarQube analysis to enforce quality standards and streamline workflows for Docker images. Scout acts as a bridge between your Docker images and SonarQube analysis.

  • Image Linking: Scout uses Git provenance information to link specific Docker image versions with the corresponding SonarQube analysis results. This allows Scout to understand which analysis applies to which image.
  • Policy Enforcement: Scout implements the “Quality gates passed” policy. This policy checks if the image’s linked SonarQube analysis adheres to the quality gates defined in SonarQube.
  • Workflow Integration: Scout integrates with your existing workflows. When a new image is pushed, Scout triggers the policy evaluation. Based on the outcome (pass/fail), Scout can initiate actions like sending notifications, blocking deployments, or triggering remediation pipelines.
  • Automated Quality Checks: Scout automates the process of applying SonarQube analysis results to Docker images, saving time and effort.
  • Gatekeeper for Deployments: The “Quality gates passed” policy enforces quality standards by preventing deployment of failing images.
  • Early Problem Detection: By leveraging SonarQube analysis within Scout, potential code issues are identified early in the development cycle.
  • Improved Collaboration: Scout fosters collaboration between developers and security teams by aligning code quality with image security assessments.

Scout acts as a management layer that leverages SonarQube analysis to enforce quality standards and streamline workflows for Docker images. SonarQube itself doesn’t directly block deployments. It provides the analysis and quality gates. Scout leverages the SonarQube analysis and enforces the quality gates defined within Scout. Based on the policy outcome (pass/fail), Scout can block deployments or trigger other actions.

Prerequisites:

To integrate Docker Scout with SonarQube, ensure that:

You need to provide Git provenance in your container images.

  1. Specifying image labels when building the image⁠
FROM alpine:3.14@sha256:eb3e4e175ba6d212ba1d6e04fc0782916c08e1c9d7b45892e9796141b1d379ae
LABEL "com.example.vendor"="Collabnix"
LABEL com.example.label-with-value="sonar"
LABEL version="1.0"
LABEL description="We are testing  \
scout integration with Sonarqube."
ENV BLUEBIRD_WARNINGS=0 \
  NODE_ENV=production \
  NODE_NO_WARNINGS=1 \
  NPM_CONFIG_LOGLEVEL=warn \
  SUPPRESS_NO_CONFIG_WARNING=true

RUN apk add --no-cache \
  nodejs

COPY package.json ./

RUN  apk add --no-cache npm \
 && npm i --no-optional \
 && npm cache clean --force \
 && apk del npm

COPY . /app

CMD ["node","/app/app.js"]

EXPOSE 3000
  1. Generating provenance attestations when building the image⁠

First you need to create a Docker container builder using buildx

docker buildx create --use --name=buildkit-container --driver=docker-container
buildkit-container

Ensure that your latest builder is docker-container

docker buildx ls
NAME/NODE             DRIVER/ENDPOINT  STATUS   BUILDKIT             PLATFORMS
buildkit-container *  docker-container
  buildkit-container0 desktop-linux    inactive
default               docker
  default             default          running  v0.11.7+d3e6c1360f6e linux/arm64, linux/amd64, linux/amd64/v2, linux/riscv64, linux/ppc64le, linux/s390x, linux/386, linux/mips64le, linux/mips64, linux/arm/v7, linux/arm/v6
desktop-linux         docker
  desktop-linux       desktop-linux    running  v0.11.7+d3e6c1360f6e linux/arm64, linux/amd64, linux/amd64/v2, linux/riscv64, linux/ppc64le, linux/s390x, linux/386, linux/mips64le, linux/mips64, linux/arm/v7, linux/arm/v6

Let’s build the Docker Image

To create a provenance attestation, pass the –attest type=provenance option to the docker buildx build command:

 docker buildx build --tag <namespace>/<image>:<version> \
    --attest type=provenance,mode=[min,max] .

Alternatively, you can use the shorthand –provenance=true option instead of –attest type=provenance. To specify the mode parameter using the shorthand option, use: –provenance=mode=max.

Here’s the actual result:

docker buildx build --tag ajeetraina/scout-demo-sonar:1.0  --attest type=provenance,mode=max . --push



...
....
 => => pushing layers                                                                             10.0s
 => => pushing manifest for docker.io/ajeetraina/scout-demo-sonar:1.0@sha256:37fd9aa92dc40b70d121  1.9s
 => [auth] ajeetraina/scout-demo-sonar:pull,push token for registry-1.docker.io

Getting Started

Step 1. Accessing Docker Scout Dashboard

Open https://scout.docker.com > Integrations > Code Quality > Click on “Manage”.

Step 2. Click “Add”

Step 3. Evaluate your images against the SonarQube quality gates defined in your projects.

Prerequisites

You need:

  • Either a SonarCloud account or access to your own SonarQube server installation.
  • (Optional) a user token with admin permissions to create the webhook in SonarQube.

Overview of SonarCloud

SonarCloud enables your development team to deliver Clean Code consistently and efficiently by seamlessly integrating into your cloud DevOps platforms and extending your CI/CD workflow. This SaaS tool catches Security Vulnerabilities, Bugs, and Code Smells in your pull requests, branches, and throughout your repository, with more than 2 billion lines of code and 120,000+ active projects analyzed every week.

SonarCloud integrates seamlessly into your GitHub workflow and provides clear guidance for resolving any Code Quality and Code Security issues detected. We empower developers and development teams of all sizes to write cleaner and safer code, across 24 programming languages (including Java, JavaScript, TypeScript, C#, Python, C++, and many more). Many popular languages can be analyzed automatically; no configuration is required!

With SonarCloud, you get:

  • Fast, precise static analysis and feedback on your code to develop Clean Code
  • Support for popular languages, frameworks, and IaC tools
  • Free analysis for open-source projects
  • Automatic analysis of pull requests and branches with results reported inline
  • IDE Support with SonarLint integration
  • Quality Gate (added as a GitHub check) acting at two different levels – first, preventing you from merging pull requests that contain issues – and later, helping you to release only clean, safe code

Next, select the configuration name of your choice.

Click Next.

Before you proceed, ensure to follow the following steps to  create a new organization under SonarCloud

Click “Analyze a New Project”

Choose “Scout Demo Service” and “Scout Demo Voting App”

Viewing the Projects

You will also require user token that you need to create via SonarQube > Security option

Step 4. Connect to Sonarqube

Step 5. Select repositories from one of your repositories

Step 6. Click on “Policies” on the top navigation bar of the Scout Dashboard

Step 7. Verify the results

Add the following workflow file

name: Build
on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened]
jobs:
  sonarcloud:
    name: SonarCloud
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis
      - name: SonarCloud Scan
        uses: SonarSource/sonarcloud-github-action@master
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Needed to get PR information, if any
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}

     

Create sonar-project.properties file under the root for your project repository

sonar.projectKey=ajeetraina_scout-demo-service
sonar.organization=ajeetraina

# This is the name and version displayed in the SonarCloud UI.
#sonar.projectName=scout-demo-service
#sonar.projectVersion=1.0


# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
#sonar.sources=.

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8

From the integration overview page, you can go directly to the Quality gates passed policy. This policy will have no results initially. To start seeing evaluation results for this policy, trigger a new SonarQube analysis of your project and push the corresponding image to a repository. For more information, refer to the Quality gates passed policy.

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index