91

I am creating a sample jenkins pipeline, here is the code.

pipeline {
    agent any 

    stages {    
        stage('test') { 
            steps { 
                sh 'echo hello'
            }            
        }
        stage('test1') { 
            steps { 
                sh 'echo $TEST'
            }            
        }
        stage('test3') {
            if (env.BRANCH_NAME == 'master') {
                echo 'I only execute on the master branch'
            } else {
                echo 'I execute elsewhere'
            }                        
        }        
    }
}

this pipeline fails with following error logs

Started by user admin
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 15: Not a valid stage section definition: "if (env.BRANCH_NAME == 'master') {
                echo 'I only execute on the master branch'
            } else {
                echo 'I execute elsewhere'
            }". Some extra configuration is required. @ line 15, column 9.
           stage('test3') {
           ^

WorkflowScript: 15: Nothing to execute within stage "test3" @ line 15, column 9.
           stage('test3') {
           ^

But when i execute the following example from this url, it executes successfully and print the else part.

node {
    stage('Example') {
        if (env.BRANCH_NAME == 'master') {
            echo 'I only execute on the master branch'
        } else {
            echo 'I execute elsewhere'
        }
    }
}

The only difference i can see is that in the working example there is no stages but in my case it has.

What is wrong here, can anyone please suggest?

4 Answers 4

205

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

2
  • I'm not sure if you will read this after so many years. In the above example can we use a variable instead of an environment variable. In my declarative pipeline, I create a variable DO_BUILD=sh(...), here DO_BUILD will have a 1 or 0 based on my shell command. And now, I want to use DO_BUILD in the if (${DO_BUILD} == '1') statement, and it doesn't work and it throws error that $ is not DSL function.
    – BaskarA
    Jan 31 at 12:11
  • You should ask a new question in this case so you can provide enough context for someone to answer your question and for other people with a similar issue to find it. You might try wrapping the dollar expression in double quotes: stackoverflow.com/a/50288263/6090676.
    – burnettk
    Jan 31 at 16:37
49

It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

stage ('Test 3: Master') {
    when { branch 'master' }
    steps { 
        echo 'I only execute on the master branch.' 
    }
}

stage ('Test 3: Dev') {
    when { not { branch 'master' } }
    steps {
        echo 'I execute on non-master branches.'
    }
}
2
  • 1
    I prefer this solution rather then using if else when there is not so much complexity! Ty! Dec 13, 2019 at 10:06
  • With 'when' condition, you are creating condition for complete stage, if it is false then complete stage will be skipped, and in case of 'if else', you still can execute 1 part of the script within the stage it will not be skipped.
    – np2807
    Mar 20, 2021 at 9:34
4

If you wanted to create a condition to execute only a stage based on expression you can use keyword when

stage ('test3'){
    when { expression { return env.BRANCH_NAME == 'master'} }
    steps {
           echo 'I only execute on the master branch.'
          }
    }
}

With the expression key word you can add any condition.

e.g. if stage is dependent on generated file in workspace.

stage ('File Dependent stage'){
 when { expression { return fileExists ('myfile') } }
    steps {
           echo "file exists"
          }
    }
}
-4
        if ( params.build_deploy == '1' ) {
            println "build_deploy 是 ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }
1
  • 7
    You can always delete it to regain rep, mate:)
    – mirekphd
    Dec 6, 2019 at 11:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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