Jenkins

Jenkins AnyOf Operation

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 fundamentals of working with the anyOf 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.
  • allOf – It specifies that all of the conditions that follow it must be true for the build step or post-build action to run.

Jenkins AnyOf Operator

The Jenkins anyOf operator allows us to define a set of nested conditional expressions. The block evaluates the specified conditions and proceeds to execute the defined steps if any of the conditions are true. If neither of the conditions is true, the steps are skipped.

We can use the anyOf operator to specify that a build should be executed if any specified conditions are met, as demonstrated in the following example:

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

In this case, the Build stage is executed if the current branch is master or the BUILD_ENV environment variable is set to prod.

Conclusion

We discussed how to use the anyOf operator in Jenkins to specify a set of nested conditions. Jenkins executes the defined steps if any of the conditions are true. Otherwise, Jenkins skips the steps.

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