It's simple. You can use if
statement in your pipeline script.
steps {
script {
if (condition) {
// do something
} else {
// do something
}
}
}
But if you want to run stage with some condition, you can use when
directive.
stage('Deploy') {
when {
expression { condition }
}
steps {
// do something
}
}
stage('Rollback') {
when {
expression { !condition }
}
steps {
// do something
}
}
This improves readability of your pipeline's stage view because skipped stage is left blank.
You might have a situation to switch the task by situation. In this case, you want to use switch
statement style operation.
You can simply use if statement pattern with various condition.
def color = getColor()
stage('Case "red"') {
when {
expression { color == 'red' }
}
steps { doSomething }
}
stage('Case "blue"') {
when {
expression { color == 'blue' }
}
steps { doOtherThing }
}
stage('default') {
when {
expression { !['red', 'blue'].contains(color) }
}
steps { doDefaultThing }
}