4

I have a multibranch pipeline that runs a Jenkinsfile of select branches. Now I need to run that same Jenkinsfile with parameters, so I figured I could use a regular pipeline.

Now all I have to do is to determine whether I run in a multibranch pipeline or not. I could check for any parameters in the build, and when there aren't any I could deduce that I'm in a multibranch pipeline:

def isMultibranchPipeline() {
    !params.any()
}

I was searching for a more direct method to know whether the script is running in a multibranch pipeline or not, but couldn't find anything like it.

towel
  • 2,094
  • 1
  • 20
  • 30
  • 1
    I was able to find a few other questions that more specifically asked how to determine if parameters were defined or not. If your situation is purely binary where all parameters exist or none do, you could use the "params." object to check rather than jenkins internal properties. https://stackoverflow.com/questions/38145508/how-to-check-if-build-parameter-is-available-in-jenkinsfile – jeubank12 Dec 17 '18 at 19:33
  • @kskid19 thanks. I wish I wouldn't have to rely on the existence of parameters (a few of my pipelines have no parameters so I still have to maintain them outside of the main source) – towel Dec 18 '18 at 08:24

2 Answers2

7

By getting the current "project" (which is a Jenkins job) you're able to know if it's a multibranch job or not thanks to its class:

import jenkins.model.Jenkins
import org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject

def isMultiBranchPipeline() {
    return Jenkins.get().getItem(currentBuild.projectName) instanceof WorkflowMultiBranchProject
}
DevAntoine
  • 1,932
  • 19
  • 24
0

if job is PipelineMultiBranchDefaultsProject previous approach is not working. I'm checking with scm object

boolean isMultiBranchPipeline() {
    try {
      if (script.scm)
        return true
    } catch (Exception e) {
      return false
    }
  }
kuzea
  • 381
  • 3
  • 3
  • This approach will work for any pipeline that's configured to take its `Jenkinsfile` from an SCM. In this case, it works if no regular pipeline is configured with an SCM. – towel Nov 13 '19 at 09:31
  • What I did in the end was to have default arguments, and pipelines with parameters would pass them – towel Nov 13 '19 at 09:36
  • that function is in shared library In my case is working with - multibranch pipelines with Default pipeline, - multibranch pipelines from SCM - with simple pipelines from SCM – kuzea Nov 13 '19 at 10:37