GitLab CI/CD: Architecting, Deploying, and Optimizing Pipelines

Optimization Security and Monitoring

Component Code Quality

Optimize your CI/CD workflow by integrating GitLab’s Code Quality analysis. This component scans your source code for complexity, duplication, style issues, and maintainability risks—helping your team merge only high-quality changes.

The image shows a GitLab documentation page about "Code Quality," detailing its features, tiers, and usage for analyzing source code quality and complexity. The sidebar and main content provide navigation and information on related topics.

Why Code Quality Matters

  • Detects potential bugs and anti-patterns early
  • Tracks complexity and duplication over time
  • Enforces coding standards and style guidelines
  • Integrates seamlessly with merge requests for inline review

How It Works

GitLab’s built-in Code Quality template leverages the open-source Code Climate engine plus additional scanners. It produces a JSON (or HTML) report consumed by GitLab to annotate merge requests and pipeline views.

The image shows a webpage from Code Climate listing supported programming languages for maintainability checks, including Ruby, Python, PHP, JavaScript, and others. It also mentions support for third-party plugins.

Note

Verify your project’s language is supported by Code Climate before enabling the component.

Feature Comparison by GitLab Tier

Different GitLab subscriptions unlock advanced Code Quality capabilities:

GitLab TierKey Features
FreeBasic maintainability and style checks
PremiumCustom scanner configuration, report artifacts
UltimateQuality dashboard, advanced analytics, MR insights

The image shows a GitLab documentation page detailing features available per tier (Free, Premium, Ultimate) for code quality. It includes a table listing features like configuring scanners and generating report artifacts, with a sidebar for navigation.

Merge Request Inline Reports

Once enabled, Code Quality issues surface directly in the Merge Request widget—categorized by severity and file location.

The image shows a GitLab documentation page about the "Merge request widget" for code quality analysis. It includes a list of code quality issues with their severity levels and file locations.

For example, a simple JavaScript function:

function init() {
  return 'foo';
  debugger;
}

Code Climate flags the unused debugger; statement as an issue.

1. Enable Code Quality in Your CI Configuration

Add the official GitLab CI/CD component at the top of your .gitlab-ci.yml:

include:
  - component: gitlab.com/gitlab-components/code-quality/[email protected]

GitLab CI/CD components are reusable jobs and templates. Browse the CI/CD Catalog (beta) to discover 99 components.

The image shows a GitLab documentation page about the CI/CD Catalog, detailing its tiers, offerings, and status, along with instructions on how to view and publish component projects.

In the Pipeline Editor, search for code-quality:

workflow: …
stages: …
variables: …
unit_testing: …
docker_build: …
# … other jobs …

The image shows a GitLab CI/CD Catalog interface with a list of components available for improving pipeline functionality. It includes a feedback section and a search bar for exploring components.

Click code-quality to view usage details and inspect its repository files:

The image shows a GitLab repository interface for a project named "Code Quality," displaying a list of files and folders with their last commit messages and update times.

Snippet from the component’s template:

code_quality:
  artifacts:
    paths:
      - gl-code-quality-report.json
  rules:
    - if: $CI_MERGE_REQUEST_ID || $CI_COMMIT_TAG || $CI_COMMIT_BRANCH

2. Add Code Quality to Your Pipeline

Start with a basic Node.js pipeline:

stages:
  - test

.prepare_nodejs_environment: &prepare_nodejs
  image: node:14
  before_script:
    - npm install

unit_testing:
  stage: test
  extends: *prepare_nodejs
  script:
    - npm test
  artifacts:
    when: always
    expire_in: 3 days
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura-coverage.xml

Include the Code Quality component before defining your jobs:

include:
  - component: gitlab.com/gitlab-components/code-quality/[email protected]

stages:
  - test

# … your existing jobs … #

Once committed, the pipeline adds a code_quality job automatically:

The image shows a GitLab interface with a pipeline editor, indicating a successful pipeline run with stages for code quality and unit testing. The sidebar includes options like Issues, Merge requests, and Pipelines.

View the Merged Configuration

Click View full config in the pipeline editor to see how your .gitlab-ci.yml merges with the Code Quality template:

code_quality:
  stage: test
  image: docker:20.10.12
  allow_failure: true
  services:
    - name: docker:20.10.12-dind
      command: ["--tls=false", "--host=tcp://0.0.0.0:2375"]
  variables:
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
  script:
    - export SOURCE_CODE=$PWD
    - docker pull -q $CI_TEMPLATE_REGISTRY_HOST/gitlab-org/ci-cd/codequality:0.96.0
    - docker run --rm \
        --volume "$SOURCE_CODE":/code \
        --volume /var/run/docker.sock:/var/run/docker.sock \
        $CI_TEMPLATE_REGISTRY_HOST/gitlab-org/ci-cd/codequality:0.96.0 /code
  artifacts:
    reports:
      codequality:
        - gl-code-quality-report.json
    expire_in: 1 week
  rules:
    - if: '$CI_COMMIT_TAG || $CI_COMMIT_BRANCH'
      when: always

By default, allow_failure: true ensures Code Quality issues don’t block merges.

3. Customize Stages & Report Formats

GitLab supports two special stages: .pre and .post. Assign code_quality to .pre for early feedback:

stages:
  - ".pre"
  - test
  - build
  - deploy
  - ".post"

include:
  - component: gitlab.com/gitlab-components/code-quality/[email protected]

code_quality:
  stage: ".pre"

To generate an HTML report instead of JSON:

code_quality:
  stage: ".pre"
  variables:
    REPORT_FORMAT: html
  artifacts:
    paths:
      - gl-code-quality-report.html
    reports:
      codequality: []

This stores gl-code-quality-report.html as a job artifact.

4. Pipeline Run & Artifacts

Triggering a commit runs both code_quality and unit_testing jobs:

The image shows a GitLab CI/CD pipeline interface for a NodeJS project, displaying stages for code quality and unit testing. The pipeline is currently running, with one job in progress.

Inspect logs to see the analysis steps:

$ export SOURCE_CODE=$PWD
$ docker pull -q $CI_TEMPLATE_REGISTRY_HOST/gitlab-org/ci-cd/codequality:0.96.0
$ docker run --rm \
    --volume "$SOURCE_CODE":/code \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    ...

Browse the HTML or JSON report via the job’s Browse link. The report groups findings by:

  • Bug Risk
  • Complexity
  • Duplication
  • Style

For inline MR annotations, GitLab uses the JSON report.

Example Findings

Bug Risk

throw new Error('Request failed.');
}).catch(function(error) {
  alert("Ooops, We have 8 planets.\nSelect a number from 0 - 8");
  console.log(error);
})

Duplication

describe('Fetching Planet Details', () => {
  it('should fetch Mercury', (done) => {
    const payload = { id: 1 };
    chai.request(server)
      .post('/planet')
      .send(payload);
      .end((err, res) => {
        res.should.have.status(200);
        res.body.should.have.property('name').eql('Mercury');
        done();
      });
  });
});

Additional Code Quality Features

Top-tier GitLab plans unlock more advanced tools:

FeatureAvailability
Pipeline view inline annotationsPremium & above
Project Quality Dashboard summariesUltimate
Merge Request Changes viewUltimate

The image shows a GitLab documentation page detailing features available per tier (Free, Premium, Ultimate) for code quality. It includes a table listing features like configuring scanners and generating report artifacts.

After review, your pipeline completes successfully:

The image shows a GitLab pipeline interface for a NodeJS project, displaying a successful pipeline run with stages for code quality and unit testing.

That’s it! You’ve integrated and customized GitLab’s Code Quality component to elevate your CI/CD standards.


Watch Video

Watch video content

Previous
Template and Types of Includes