Search code examples
jenkinsmultibranch-pipeline

Determine whether a Jenkinsfile runs from a multibranch pipeline


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.


Solution

  • 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
    }