using Matrix generator in Gitlab and GitHub CICD

Published by

on

Matrix Generators

A matrix generator refers to a feature that allows you to define and generate a matrix of different build or test configurations, which can then be used to run jobs in parallel on various combinations of the defined parameters. This is often used to achieve better resource utilization and faster job execution in your continuous integration (CI) pipeline.

Generators are responsible for generating parameters, which are then rendered into the template

Github Example:

name: Matrix Generator Example

on:
  push:
    branches:
      - main

jobs:
  build:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macOS-latest]
        node_version: [12, 14, 16]

    runs-on: ${{ matrix.os }}

    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node_version }}

    - name: Install dependencies
      run: npm install

    - name: Build and test
      run: npm run build && npm test

In this example, the matrix generator is defined under the strategy section of the build job. It generates different combinations of operating systems (os) and Node.js versions (node_version). The workflow will create a separate job for each combination in the matrix, resulting in parallel execution of these jobs.

GitLab Example:


stages:
  - build
  - test


demo:
  stage: build
  parallel:
    matrix:
      - names: ["test1", "test2"]
  
  script:
    - echo "hello ${names}"

In the Gitlab Matrix generator example, we are generating a combination of parameters for names, with this combination demo stage is able to generate two stages demo:[test1] and demo:[test2] based on the parameters and it is a able to successfully inject the variable into the job.
In the log output of the job, echo ${names} was successfully able to inject test1 and test2 into the names variable respectively.

Use cases:

These type of matrix based generators are extremely useful in avoiding repetitive jobs. For example, if we have four jobs which deploys to four different clusters instead of declaring them in the gitlab file. if we can use matrix generators we would be able to successfully reduce the amount of code that we type into Gitlab file.

Leave a comment

Discover more from dwarak

Subscribe to the newsletter to keep reading and get access to the full archive.

Continue Reading with out subscribing