pipeline {
agent any
stages {
stage('Build') {
when {
branch 'main'
}
steps {
echo 'Building main branch'
}
}
stage('Feature Build') {
when {
branch pattern: 'feature-.*', comparator: 'regex'
}
steps {
echo 'Building feature branch'
}
}
}
}The 'when' condition for the 'Feature Build' stage uses a regex pattern matching branches starting with 'feature-'. Since the branch is 'feature-xyz', this stage runs and outputs 'Building feature branch'. The 'Build' stage only runs on 'main' branch.
Option A uses the correct 'when { branch 'branchName' }' syntax for each stage. Option A tries to combine branches with '||' which is invalid syntax. Option A uses 'branch == 'main'' which is not valid in declarative pipeline. Option A uses '&&' which is invalid for branch condition.
pipeline {
agent any
stages {
stage('Build') {
when {
branch == 'main'
}
steps {
echo 'Building main'
}
}
}
}The 'when' condition for branch must use 'branch 'branchName'' syntax, not an equality check like 'branch == 'main''. This causes a syntax error.
Stages with 'when' conditions that do not match the current branch are simply skipped. The pipeline continues running other stages that match or have no conditions.
Using a single Jenkinsfile with 'when' conditions is the best practice. It keeps configuration centralized and leverages Jenkins multi-branch pipeline features. Other options increase complexity and maintenance overhead.