How to Use a Matrix in a Jenkins Declarative Pipeline
The matrix directive runs a set of stages across every combination of axis values, generating a cell per combination in parallel.
Define axes with named values inside a matrix block; Jenkins runs the inner stages once per cell. Use excludes to skip combinations and per-axis env in environment.
Matrix over OS and version
Each OS-by-version cell runs the inner stages; an exclude drops one combination.
pipeline {
agent none
stages {
stage('Test') {
matrix {
axes {
axis { name 'OS'; values 'linux', 'windows' }
axis { name 'NODE'; values '18', '20' }
}
excludes {
exclude {
axis { name 'OS'; values 'windows' }
axis { name 'NODE'; values '18' }
}
}
agent { label "${OS}" }
stages {
stage('Run') {
steps { sh "npm test # node ${NODE}" }
}
}
}
}
}
}Gotchas
- Axis values become environment variables (
${OS},${NODE}) inside the matrix cells. - Use
excludesto prune combinations that do not make sense, avoiding wasted cells. - Each cell can target a different
agent; setagent noneat the pipeline level so cells choose their own.
Verify it actually works
Validate the pipeline definition against the running controller before committing. Jenkins parses declarative pipelines strictly, and a syntax error surfaces as a failed build rather than a clear parse message.
# validate a Jenkinsfile against the live controller
curl -X POST -F "jenkinsfile=<Jenkinsfile" \
https://your-jenkins/pipeline-model-converter/validate
# replay a build with modified script to test a change without committing
# Build page -> Replay -> edit -> RunAgent and workspace assumptions that break in CI
- An agent label that matches no online agent leaves the build queued indefinitely rather than failing.
- Workspaces are reused between builds by default, so stale files from a previous run can mask or cause failures. Use
cleanWs()or a fresh workspace when correctness matters. - Tools resolved from the controller PATH are not necessarily on the agent PATH. Declare them in a
toolsblock or install them in the pipeline. - Credentials bound with
withCredentialsare masked in logs but still visible to any process you launch; avoid passing them as command-line arguments.
Key takeaways
- The
matrixdirective runs stages across axis combinations. - Axis values are exposed as environment variables in cells.
- Use
excludesto skip combinations andagentper cell.