Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins pipeline conditional branch builds

Using a multibranch pipeline I'd like trigger a slightly different build and deploy procedure depending on which git branch has triggered the build.

The two approaches I can think of are : 1) Use a different jenkins file in each branch 2) Use a series of when {branch 'X'} blocks in the jenkins file

The first approach mean I'll need to be careful when merging branches which I know I'll forget to be at some point.

The second approach is pretty messy but does mean I can use just one Jenkins file.

I can't believe there isn't a better way than these two approaches.

like image 799
Andy Rich Avatar asked Feb 16 '18 13:02

Andy Rich


1 Answers

Even though I am not a DevOps expert, I can suggest using when conditions in your pipeline so that some stages are only triggered if when conditions are satisfied.

pipeline {

    triggers {
      # triggered by changes in every branch
    }
    stages {
      stage('first-stage'){
        when { anyOf { branch 'feature-branch/*'; branch 'master' } }
        steps{
          ....
        }
      }
      stage('second-stage'){
        when {
          not {
            branch 'release/*'
          }
          not {
            branch 'staging'
          }
        }
        steps{
          ....
        }
      }

    }
}

Or you can have multiple job templates using job-builder plugin. Then you can create different projects with different branch parameters materializing job templates. This is a bit complex and I would go with the "pipeline with when conditions" above.

This link may also help: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

like image 158
Muatik Avatar answered Nov 27 '22 03:11

Muatik