Contents

Jenkins Conditions and Confirmations

Understand how to use conditions and user input confirmation in Jenkins

Website Visitors:

Using a conditional expression, you can control Jenkins stage to run when a condition is validated. On the other hand, you can also pause the script for user input when running a stage. In this tutorial, we’ll explain what are conditions, user input confirmation, and How does Jenkins handle them?

Find out here!

Conditional Expressions

Using the when {} block your pipeline can determine whether to run the stage or not, depending on the given condition. When block should contain atleast one condition. If when block contains more than one condition, all conditions should result in true in order to run the stage. The when block/condition should be updated in the stage block.

Built-in Conditions

These are the built-in conditions available:

branch

Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch 'master' }. Note that this only works on a multibranch Pipeline.

The optional parameter comparator may be added after an attribute to specify how any patterns are evaluated for a match: EQUALS for a simple string comparison, GLOB (the default) for an ANT style path glob (same as for example changeset), or REGEXP for regular expression matching. For example: when { branch pattern: "release-\\d+", comparator: "REGEXP"}

buildingTag

Execute the stage when the build is building a tag. Example: when { buildingTag() }

changelog

Execute the stage if the build’s SCM changelog contains a given regular expression pattern. For example: when { changelog '.*^\\[DEPENDENCY\\] .+$' }

changeset

Execute the stage if the build’s SCM changeset contains one or more files matching the given pattern. Example: when { changeset "**/*.js" }

The optional parameter comparator may be added after an attribute to specify how any patterns are evaluated for a match: EQUALS for a simple string comparison, GLOB (the default) for an ANT style path glob case insensitive, this can be turned off with the caseSensitive parameter, or REGEXP for regular expression matching. For example: when { changeset pattern: ".**TEST\\.java", comparator: "REGEXP" }** or when { changeset pattern: "*/*TEST.java", caseSensitive: true }

changeRequest

Executes the stage if the current build is for a “change request” (a.k.a. Pull Request on GitHub and Bitbucket, Merge Request on GitLab, Change in Gerrit, etc.). When no parameters are passed the stage runs on every change request, for example: when { changeRequest() }.

By adding a filter attribute with parameter to the change request, the stage can be made to run only on matching change requests. Possible attributes are id, target, branch, fork, url, title, author, authorDisplayName, and authorEmail. Each of these corresponds to a CHANGE_* environment variable, for example: when { changeRequest target: 'master' }.

The optional parameter comparator may be added after an attribute to specify how any patterns are evaluated for a match: EQUALS for a simple string comparison (the default), GLOB for an ANT style path glob (same as for example changeset), or REGEXP for regular expression matching. Example: when { changeRequest authorEmail: "[\\w_-.]+@example.com", comparator: 'REGEXP' }

environment

Execute the stage when the specified environment variable is set to the given value, for example: when { environment name: 'DEPLOY_TO', value: 'production' }

equals

Execute the stage when the expected value is equal to the actual value, for example: when { equals expected: 2, actual: currentBuild.number }

expression

Execute the stage when the specified Groovy expression evaluates to true, for example: when { expression { return params.DEBUG_BUILD } } Note that when returning strings from your expressions they must be converted to booleans or return null to evaluate to false. Simply returning “0” or “false” will still evaluate to “true”.

tag

Execute the stage if the TAG_NAME variable matches the given pattern. Example: when { tag "release-*" }. If an empty pattern is provided the stage will execute if the TAG_NAME variable exists (same as buildingTag()).

The optional parameter comparator may be added after an attribute to specify how any patterns are evaluated for a match: EQUALS for a simple string comparison, GLOB (the default) for an ANT style path glob (same as for example changeset), or REGEXP for regular expression matching. For example: when { tag pattern: "release-\\d+", comparator: "REGEXP"}

not

Execute the stage when the nested condition is false. Must contain one condition. For example: when { not { branch 'master' } }

allOf

Execute the stage when all of the nested conditions are true. Must contain at least one condition. For example: when { allOf { branch 'master'; environment name: 'DEPLOY_TO', value: 'production' } }

anyOf

**Execute **the stage when at least one of the nested conditions is true. Must contain at least one condition. For example: when { anyOf { branch 'master'; branch 'staging' } }

triggeredBy

Execute the stage when the current build has been triggered by the param given. For example:

  • when { triggeredBy 'SCMTrigger' }

  • when { triggeredBy 'TimerTrigger' }

  • when { triggeredBy 'BuildUpstreamCause' }

  • when { triggeredBy cause: "UserIdCause", detail: "vlinde" }

Source

Sample when condition

1
2
3
4
5
when {
    expression {
        params.ENVIRONMENT == 'development'
    }
}

Pause script for confirmation

Along with conditions, you can also set a input step so that the script pause at the input step requiring an input from the user. Input allows you to prompt for input when running a stage. You can also setup a custom message in setting up the input step.

The stage will pause after any options have been applied, and before entering the agent block for that stage or evaluating the when condition of the stage. If the input is approved, the stage will then continue. Any parameters provided as part of the input submission will be available in the environment for the rest of the stage.

Configuration options

message - This will be presented to the user when they go to submit the input.

id - An optional identifier for this input. Defaults to the stage name.

ok - Optional text for the “ok” button on the input form.

submitter An optional comma-separated list of users or external group names who are allowed to submit this input. Defaults to allowing any user.

submitterParameter - An optional name of an environment variable to set with the submitter name, if present.

parameters - An optional list of parameters to prompt the submitter to provide. See parameters for more information.    

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
pipeline {
    agent any
    stages {
        stage('Example') {
            input {
                message "Should we continue?"
                ok "Yes, we should."
                submitter "alice,bob"
                parameters {
                    string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
                }
            }
            steps {
                echo "Hello, ${PERSON}, nice to meet you."
            }
        }
    }
}

Second example: In the below example, When you run, you will be prompted to select Dev, Test or Prod environments. If you select Dev or Test stages they run the build directly. But when you run the Test stage, it waits for user input to either select Deploy or Abort. Build will complete only when you select any of the option. If not, build will wait for your input as we have added an input block in the prod stage.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
pipeline {
    agent any
    parameters {
        choice(name: 'Environment',choices:['Dev', 'Test', 'Prod'], description: "Choose your environment")
    }
    stages {
        stage ('DevStage') {
            when {
                expression { params.Environment == 'Dev'}
            }
            steps {
                echo "Bulding Dev stage without prompt"
            }
        }
        stage ('TestStage') {
            when {
                expression {params.Environment == 'Test'}
            }
            steps {
                echo "Building Test stage without prompt"
            }
        }
        stage ('ProdStage') {
            when {
                expression {params.Environment == 'Prod'}
            }
            steps {
                input message: 'Confirmation needed for Production deployment', ok: 'Deploy'
                echo "Building Prod stage with confirmation"
            }

        }
    }

}

You can also add other parameters to above script and use them in your code.

1
2
3
4
5
6
7
8
9
parameters {
        choice(name: 'Environment',choices:['Dev', 'Test', 'Prod'], description: "Choose your environment")
        password(name:'Password', defaultValue: 'StrongPwd', description:'Password Stage')
        text(name:'log', defaultValue: 'This is log', description: "Enter build log detail")
    }

// In the steps refer to the parameters as:
echo "password is ${params.Password}"
echo "${params.log}"

Suggested Article

Now that you know about Jenkins conditions and confirmations, continue reading our other article Jenkins pipeline here. All other DevOps categories are listed here: DevOps Tools. Have a look at the posts as per your topic of interest.

Conclusion

In this tutorial, we’ve explained how to use conditions and confirmations in Jenkins. We’ve also demonstrated examples for all the topics that are discussed. We hope you have learned something new in this article.

Please feel free to share your thoughts about this article in the comments section below.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.