Jenkins

Jenkinsfile If Else

Control flow refers to the order in which instructions in a computer program are executed. It allows a programmer to specify the steps that should be taken based on different conditions or inputs, allowing the program to make decisions and perform different actions depending on the current state.

In Jenkins, control flow can be achieved using various constructs such as if and else statements, when clauses, and parallel blocks.

This brief tutorial will explore the fundamentals of working with control flow blocks in Jenkins using if and else blocks.

Jenkins If Else Block

The following expresses the syntax of an if and else block in a declarative pipeline script:

if ( condition ) {
  // commands to execute if the condition is true
} else {
  // commands to execute if the condition is false
}

The condition must evaluate to a Boolean value.

Example

The following example demonstrates how we can use an if-else block inside a declararitive pipeline Jenkinsfile:

def arch = 'amd64';
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
                if ($arch == 'i386') {
                    echo 'Supported Architecture'
                } else {
                    echo 'Unsupported Architecture'
                }
            }
        }
    }


}

The pipeline script above defines a single stage with a single step, an if block. The if block compares the value of the arch variable to the string ‘i386’, and if they are equal, it prints the message ‘Supported Architecture.’ If the values are unequal, it prints the message ‘Unsupported Architecture.’

Conclusion

This tutorial taught you how to introduce control flow in a Jenkinsfile using an if-else block. Jenkins supports other control flow options, such as try-catch and when. Check our tutorials on the topic to learn how you can work with these pipeline features.

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