0

I want to use when on branch condition. The Jenkinsfile is like this

 stages{
        stage('Checkout project branch master'){
            steps{             
                withCredentials([sshUserPrivateKey(credentialsId: 'credential', keyFileVariable: 'CREDENTIAL')]) {}
                git branch: 'develop', credentialsId: 'credential', url: 'git@bitbucket.org:user/demopipelinejenkinsfile.git'
            }
        }   
        stage('develop'){
             steps {
                   echo 'on branch develop`
             }
        }
        stage('any_branch'){                  
             environment {
                   GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
                   }
             steps{
                   echo "${env.GIT_BRANCH}"
                  }
        }
 }

The console output shows that the stage develop is skipped due to condition. However, the last stage still echoes the current branch is "develop"

Question How to use when with branch in Pipeline project (not Multibranch project)

  • Can you provide the exact output of your error when running the pipeline? – PrestonM Oct 31 '18 at 16:27
  • Also, I'm assuming you are using declarative pipelines, is that correct? – PrestonM Oct 31 '18 at 16:27
  • 2
    Your jenkinsfile stage develop doesn't have a when condition as seen above ? Are you able to provide the when condition you are using ? You can use something like when { branch 'develop' } – ben5556 Nov 4 '18 at 0:18
1

This is the way to go:

stage('Deploy'){
  when {
    expression {env.GIT_BRANCH == 'origin/master'}
  }
  steps {
    ....
   }
}

Take care, this is only working with the declarative syntax.

The environment step is used to "set up the environment" meaning this is the place to declare environmental variables.

Also, in my case I did not declare the GIT_BRANCH var myself. But jenkins provides it as an environmental (therefore "env.GIT_BRANCH") variable if you did "checkout scm" to checkout your repository. If you want to check all the available env vars, do this as a step: sh 'printenv'

check out this article for more info: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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