CircleCI has a variety of features that make it configurable, flexible, and efficient. Some of these are orbs, reusable config, pipeline variables, and a UI that makes viewing status and fixing builds more efficient than ever. Matrix jobs are another tool for your efficiency workbench.

What are matrix jobs?

Matrix jobs are a developer’s secret weapon to write simple configuration for complicated software. With only a few lines of config, you can go from a single test to a more comprehensive test suite, or from one task into a parallelized batch of related work. CircleCI has support for matrices as part of our workflow syntax built in. Our matrix implementation works in tandem with our parameterized jobs to serve many use cases.

Suppose I am developing a widely-used open-source JavaScript library. Before building and shipping a new version of the library, I want to test my code on a few different versions of Node.js (10 through 13), and also confirm it works on both Linux and macOS. This means I have a two-dimensional “matrix” of cases:

So how do we express this in CircleCI? First we will define two executors representing the operating systems we want to test on. Then, we must create a parameterized job, called test, whose parameters match the dimensions of the matrix.

version: 2.1

executors:
  linux:
    docker:
      - image: cimg/base:2020.01
  macos:
    macos:
      xcode: 11.4

orbs:
  node: circleci/node@2.0.0

jobs:
  test:
    parameters:
      os:
        type: executor
      node-version:
        type: string
    executor: << parameters.os >>
    steps:
      - checkout
      - node/install:
          node-version: << parameters.node-version >>
          install-yarn: true
      - run: yarn test

Then we will create a workflow that invokes this job using a matrix:

workflows:
  all-tests:
    jobs:
      - test:
          matrix:
            parameters:
              os: [linux, macos]
              node-version: ["10.9.0", "11.9.0", "12.9.1", "13.9.0"]

Pushing this config and examining my pipeline result shows me that I have created a workflow of 8 jobs that covers all the bases:

For another look at setting up and running matrix jobs, check out this video.

Matrix jobs are available to all CircleCI users. This feature is powerful because it works with any combination of job parameters, generating human-readable names for each individual job. You are not restricted to a finite number of ways to do cross-platform testing, such as just the Node.js version and operating system. It can be anything representable as a job parameter. The docs include even more advanced features, like excluding specific combinations and using templated dependencies to create complex workflows.

To learn more about the other features mentioned in this post, visit these links: