161

How do you run a build step/stage only if building a specific branch?

For example, run a deployment step only if the branch is called deployment, leaving everything else the same.

5 Answers 5

291

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

4
  • 1
    can I use this for the post build actions?
    – Doug
    Commented Feb 14, 2018 at 9:03
  • 1
    I find Jenkins spins up the specified agent even if the when{} condition evaluates to false. :(
    – Hakanai
    Commented May 6, 2019 at 4:58
  • 2
    @Trejkaz you can now use beforeAgent true to avoid that
    – Nick Jones
    Commented Oct 18, 2019 at 10:33
  • 1
    @NickJones indeed, beforeAgent is now a workaround for that.
    – Hakanai
    Commented Oct 21, 2019 at 1:32
61

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       
7
  • 7
    if should be before stage or after ?
    – Jet
    Commented Oct 27, 2017 at 8:52
  • 7
    Before stage, stages can be inside if branches Commented Oct 27, 2017 at 14:19
  • don't think the placement actually matters
    – omu_negru
    Commented Sep 19, 2018 at 9:05
  • 9
    I can't get this work with a declarative pipeline. Does this work with declarative pipelines? WorkflowScript: 9: Expected a stage @ line 9, column 9. if (env.BRANCH_NAME == "deployment") { WorkflowScript: 8: No stages specified @ line 8, column 5. stages { Commented Jan 11, 2019 at 22:53
  • 11
    this only works in scripted pipelines. for declarative pipelines, you should use script {} inside the step. Commented Jul 31, 2019 at 17:31
15

I'm adding this answer to explicitly mention using a condition in a step in contrast to a stage, both within declarative pipelines.

Condition in a stage of a declarative pipeline

As already shown by @Chandan Nayak and others, this can be done based on when as in

stage('myConditionalStage') {
    when {
        branch 'myBranch'
    }
    steps {
        echo 'triggered by myBranch'
    }
}

So the stage myConditionalStage will only be run if triggered by a push to myBranch.

Condition in a step of a declarative pipeline's stage

If you however need a condition within the steps section of a stage, you can use Groovy syntax (if/else in this case) that is used in Scripted pipelines. In case of a Declarative pipeline you have to put it into a script block as follows:

stage('myStage') {
    steps {
        echo 'within myStage'
        script {
            if (env.BRANCH_NAME == "myBranch") {
                echo 'triggered by myBranch'
            } else {
                echo 'triggered by something else'
            }
        }
    }
}

For a Scripted pipeline, you can use it without the script block as shown by @Krzysztof Krasoń

8

According to other answers I am adding the parallel stages scenario:

pipeline {
    agent any
    stages {
        stage('some parallel stage') {
            parallel {
                stage('parallel stage 1') {
                    when {
                      expression { ENV == "something" }
                    }
                    steps {
                        echo 'something'
                    }
                }
                stage('parallel stage 2') {
                    steps {
                        echo 'something'
                    }
                }
            }
        }
    }
}
1
  • is there any way to have a condition in step? I am using if else in step. I have parallel stage for datacenter 1 and datacenter 2. Then in each datacenter, I have to either install or uninstall depending on option chosen Commented Jul 14, 2022 at 15:22
-1

I created more nested stages as follows:

    pipeline {
     
      // Agent To Run On
      agent none
    
      stages {

   
    // Processing OpenCV Optimizer
    stage('OpenCV Processing'){

      when {
          expression { inputOptimizer == "OpenCV DNN" }
      }


      stages {

        // Checkout and Compile stage
        stage('SCM Checkout & Build'){

          parallel {

            stage('Test On Windows') {
                agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "first stage"
                }
            }//Test On Windows

            stage('Test On Linux') {
                agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "second stage"
                }

            }//Test On Linux

            stage('Testing '){
              agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "second dddd"
                }
            }//Testing

          }

        }

        // Docker Build
        stage("Docker Build"){
      
          steps {

            echo "Build stage"

          }
        
        }

      }

    }


    // Processing OpenVino Optimizer
    stage('OpenVino Processing'){

      when {
          expression { inputOptimizer == "OpenVino CPU Yolov7" }
      }


      stages {

        // Checkout and Compile stage
        stage('SCM Checkout & Build'){

          parallel {

            stage('Test On Windows') {
                agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "first stage"
                }
            }//Test On Windows

            stage('Test On Linux') {
                agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "second stage"
                }

            }//Test On Linux

            stage('Testing '){
              agent {
                    label "Stagging-Node"
                }
                steps {
                    echo "second dddd"
                }
            }//Testing

          }

        }

        // Docker Build
        stage("Docker Build"){
      
          steps {

            echo "Build stage"

          }
        
        }

      }

    }
      
  }//end of stages

}//end of pipeline
 

Not the answer you're looking for? Browse other questions tagged or ask your own question.