Jenkins

Jenkins AllOf Operator

We can use the when expression in a Jenkinsfile to specify the conditions under which a particular build step or post-build action should be executed. It allows you to specify a Boolean expression that determines whether the build step or post-build action should be run.

This tutorial covers the basics of using the allOf operator in a Jenkins when expression.

Jenkins When Expression

The when expression must contain at least one Boolean condition. You can also combine multiple conditions, but all the specified conditions must evaluate true for the block to run.

The following shows the syntax of the when expression in Jenkins:

when {
    <condition>
}

In this case, the <condition> specifies the Boolean expression that is evaluated before running or not running the build step or post-build action.

There are several types of conditions that you can use in the when expression, including the following:

  • Branch – It specifies a branch name or a regular expression that is used to match against the current branch.
  • expression – It specifies a Groovy expression that is evaluated to determine whether the build step or post-build action should be run.
  • not – It negates the condition that follows it.
  • allOf – It specifies that all of the conditions that follow it must be true for the build step or post-build action to run.
  • anyOf – It specifies that at least one of the conditions that follow it must be true for the build step or post-build action to run.

Let us look at an example pipeline on how we can use the when expression in Jenkins.

Jenkins AllOf Operator

We can use the allOf operator in a when clause to specify that a build should be executed only if all specified conditions are met. An example demonstration is as follows:

pipeline {
    agent any
    stages {
        stage('Build') {
            when {
                allOf {
                    branch 'master'
                    environment name: 'BUILD_ENV', value: 'prod'
                }
            }
            steps {
                echo "Build step executed"
            }
        }
    }
}

In the provided example, Jenkins only executes the Build stage if the current branch is master and the BUILD_ENV environment variable is set to prod. If neither of the specified conditions is true, the entire stage is skipped.

Conclusion

This short tutorial taught us how to use the allOf operator in a Jenkins when clause. The allOf operator allows us to nest a series of conditionals and only executes a given step when all of the defined conditions are true.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list