[jenkins] Jenkins pipeline if else not working

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?

This question is related to jenkins groovy

The answer is


        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()
        }

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.'
    }
}