21

I have a multibranch job set to run any branch with a Jenkinsfile.

I have some options I can think of if I want to remove a branch from the list of jobs running for the multi-branch pipeline.

  1. I can delete the branch
  2. I can delete the Jenkinsfile in that branch

The second solution is good, except I need to commit and push that to the git repo for my branch, and if that branch is merged into another branch it blows away the Jenkinsfile.

What is the best way to disable only some branches of a multibranch pipeline?

030
  • 13,383
  • 17
  • 76
  • 178
David West
  • 1,533
  • 3
  • 18
  • 25

3 Answers3

31

Jenkins can filter branches in a multibranch pipeline by name using a wildcard or regular expression.

jenkins filter branches

casey vega
  • 748
  • 7
  • 12
2

Instead of configuring it in the UI (as perfectly described by casey vega's answer, you can also do this within your Jenkinsfile:

Declarative Pipeline

Add the following condition within any stage directive:

when { anyOf { branch 'master'; branch 'release/**' } }

As you can see, it's possible to use exact branch names as well as some wildcards (ANT style path glob pattern). It's also possible to use regex and some more fancy conditions and combinations. Please have a look at Jenkins' offical docs on the when directive for reference and detailed information.

Scripted Pipeline

Just enclose the part you want to have run conditionally in the following code:

if (env.BRANCH_NAME == 'master' || (env.BRANCH_NAME).startsWith('release/')) {
  // Your Pipeline goes here
}

This can be used almost everywhere within your (scripted) Jenkinsfile. As you can see, it's just some simple string comparison. For more complex Regex comparisons, take a look at Groovy's Find and Match operators, which also work fine here.

Conclusion

I would prefer using this method (although I recommended it otherwise some time ago), as you can then check-in your pipeline configuration into your source control and you're more on the Configuration-as-Code approach as when you configure it in your Jenkins UI.

biolauri
  • 121
  • 2
1

Simply delete the Jenkinsfile on the branch(es) you don't want to have corresponding branch jobs for. This will delete the branch job (of course, iff you have set your "Orphaned Item Strategy" appropriately).

From the perspective of a Jenkins Multibranch Pipeline Project, this has the same effect as deleting the branch. This is because it is simply scanning for branches that contain Jenkinsfiles as its criterion for when to create (or delete) a corresponding branch job.

Revert the commit to restore the Jenkinsfile if/when you need the branch job again.

timblaktu
  • 151
  • 3