Search code examples
jenkinsjenkins-plugins

Jenkins Pipeline Template Catalog Only build master and main branches


I am trying to setup a Pipeline Template Catalog that only builds main and master branches.

It works if I only define one branch name, for example master by saying that I want the NoTriggerBranchProperty for everything not master. Relevant portion of my template.yaml file:

multibranch:
  branchSource:
    git:
      remote: '${repo}'
      credentialsId: '${credentialsId}'
    strategy:
      $class: NamedExceptionsBranchPropertyStrategy
      namedExceptions:
        - name: "!master"
          props:
          - $class: NoTriggerBranchProperty
    buildStrategies:
      - $class: SkipInitialBuildOnFirstBranchIndexing

According to the docs I can append names, so !master,!main should work, but it doesn't. It actually makes all the branches not trigger on SCM changes.

I took it a step further and looked at the match code being used by Cloudbees here and as far as I can tell !master,!main should work fine. I suspect I have a logic error in my process because I am trying to invert the branch names to trigger them while using the no trigger property.


Solution

  • After a full 8 hours of testing I finally solved this problem.

    Looking at the NamedExceptionsBranchPropertyStrategy code it became obvious that !main,!master will not work because NamedExceptionsBranchPropertyStrategy.isMatch functions as an || for two names. As such the first name, in this example !main returns true and since it's a match, it breaks the entire logic chain.

    Instead, the solution is

    multibranch:
      branchSource:
        git:
          remote: '${repo}'
          credentialsId: '${credentialsId}'
        strategy:
          $class: NamedExceptionsBranchPropertyStrategy
          namedExceptions:
            - name: "master,main"
          defaultProperties:
            - $class: NoTriggerBranchProperty
        buildStrategies:
          - $class: SkipInitialBuildOnFirstBranchIndexing
    

    Basically by default do not trigger, except for the two named exceptions, master and main. This is the way to support building only specific branches (two or more) and not building the rest.

    As a prerequisite, you need to have the basic-branch-build-strategies-plugin installed.