Skip to content
Latchkey

How to Use a Matrix in a Scripted Pipeline in Jenkins

Scripted pipelines build a matrix by constructing parallel branches in Groovy.

Declarative pipelines have a matrix directive, but scripted ones build the same effect by looping over values, creating a closure per combination, and handing the map to parallel.

Generate parallel branches over versions

Build a map of node version to a closure, then run them in parallel.

Jenkinsfile
node {
  def versions = ['18', '20', '22']
  def branches = [:]
  for (v in versions) {
    def version = v
    branches["node-${version}"] = {
      docker.image("node:${version}").inside {
        checkout scm
        sh 'npm ci && npm test'
      }
    }
  }
  parallel branches
}

Notes

  • Capture the loop variable into a local (def version = v) so each closure binds its own value.
  • parallel runs all branches at once; throttle with the lock step if they contend for a resource.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →