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
How to Lock a Resource for Concurrency in JenkinsSerialize access to a shared resource like a staging environment in Jenkins using the lock step from the Lock…
How to Send Email on Failure in JenkinsNotify your team when a Jenkins build breaks by sending an email from the post failure block using the Email…