Skip to content

Instantly share code, notes, and snippets.

@basuke
Last active May 25, 2023 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basuke/b48e79cca8d434d322e194d0c62c574e to your computer and use it in GitHub Desktop.
Save basuke/b48e79cca8d434d322e194d0c62c574e to your computer and use it in GitHub Desktop.
Implementing Control Flow in Jenkins

if statement pattern

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.

switch statement pattern

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 }
}

do while loop pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment