HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Jenkins declarative pipeline: use branch if it exist

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
declarativejenkinsexistbranchpipelineuse

Problem

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?

Solution

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

checkout resolveScm(source: [$class: 'GitSCMSource',
                             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.

Code Snippets

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'])

Context

StackExchange DevOps Q#3866, answer score: 5

Revisions (0)

No revisions yet.