5

I'm currently trying to adopt my declarative pipeline in the following way:

I have multiple stages, some apply for all branches, some only for specific names.

What I'm now searching for is a way to get a when condition for the existance of a branch like this:

if branch b exist
   checkout branch b
else
   checkout branch a

Sadly I haven't found a solution for it. I'm pretty sure there is a way using the git plugin though.

There's a StackOverflow solution for scripted pipelines, but I can't translate them though.

Can someone help me with this or point me at the right direction?

papanito
  • 283
  • 2
  • 14
Hoall
  • 53
  • 1
  • 1
  • 5

4 Answers4

5

There's a resolveScm step implemented by the Pipeline: Multibranch plugin:

checkout resolveScm(source: [$class: 'GitSCMSource',
                             credentialsId: '<credentialsId>',
                             id: '_',
                             remote: 'https://your.git.remote/repository.git',
                             traits: [[$class: 'jenkins.plugins.git.traits.BranchDiscoveryTrait']]],
                    targets: [BRANCH_NAME, 'master'])

Above procedure will look whether $BRANCH_NAME exists, check it out if yes and check out master otherwise.

mrlov
  • 3
  • 2
astriffe
  • 51
  • 1
  • 3
4

When using Declarative Pipelines you can achieve the goal of running some steps only for certain branches by using the when directive with the build-in condition branch:

branch Execute the stage when the branch being built matches the branch pattern (ANT style path glob) given, for example: when { branch 'master' }. Note that this only works on a multibranch Pipeline.

pipeline {
    agent any 
    stages { 
        stage("Build") {
            when { branch "master" }
            steps { 
               echo "I am a master branch"
            }
        }
    }
}

If you use Scripted Pipeline, you may also access the BRANCH_NAME from environment variable and do something with it:

if (env.BRANCH_NAME == 'master') {
   //do something
}

Also have a look at Flow Control to understand how you can control the flow of your pipeline.

papanito
  • 283
  • 2
  • 14
2

Sometimes it is easier to ask forgiveness than permission.

Instead of trying to figure out whether branch b exists, just try to check it out.

If it fails, checkout branch a.

script {
    try {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'b']],
                userRemoteConfigs: [[url: url]]
        ])
    }
    catch (Exception e) {
        checkout([
                $class: 'GitSCM',
                branches: [[name: 'a']],
                userRemoteConfigs: [[url: url]]
        ])
    }
}
cowlinator
  • 129
  • 4
1
pipeline {
  agent any 
  stages { 
    stage('Tests') {
      when {
        branch 'master'
      }
      steps {
        echo 'foo'
      } 
   }
}
casey vega
  • 748
  • 7
  • 12
Ram
  • 139
  • 3