Search code examples
gitjenkinsbuildjenkins-pipeline

Jenkins pipeline job checkout changed feature branch


I have the following stage in my jenkins pipeline to get all branches of a project. I would like to trigger a build job, if one branch in project has changed on the changed branch.

First detect the changed branch and then checkout this specific branch out (I know that a webhook from bitbucket/github to jenkins would work.).

checkout all branches in project:

    stage ("Code pull"){
        steps{
         checkout([
            $class: 'GitSCM', branches: [[name: '*/*']],
            extensions: [[$class: 'CleanCheckout']], 
            userRemoteConfigs: [[  credentialsId:'bitbucket', url: 'my_git_repo']] 
            ])

If I new the branch something like that works fine

        stage ("Code pull"){
        steps{
             git branch: "master",
             credentialsId: 'bitbucket',
             url: 'my_repo'
            }
    }

but I would like to test any changed branch in a specific repository. Maybe there is a way to iterate over all branches and something like that:

 when { anyOf { branch 'feature-branch/*'; branch 'master' } }
    steps{
      ....git checkout the one with changes 
    }

Solution

  • I propose to use a multibranch pipeline. This simplifies the work you would like to do. The multibranch pipeline keeps track of all your branches and builds only the ones that were changed. You can even filter out branches that doesn’t need a build (e.g. feature branches).

    enter image description here

    After this, you can select the relevant branches. You have multiple options to do this, now I attached one sample. In case the branch is not part of the selected branches list, then the pipeline will not start.

    enter image description here

    In your Jenkinsfile, you just have to write def scmVars = checkout scm. This command will clone the repository and checks out the branch that was changed.