Search code examples
githubjenkinscontinuous-integrationjenkins-pipelinejenkins-blueocean

Limit which branch is built by Jenkins pipeline?


I am currently configuring a Jenkins server hosted on a Docker container in AWS.

I am using BlueOcean to configure a repository.

Right now, the pipeline scans all branches on a repository to detect Jenkinsfiles and then will automatically build on that branch if it detects changes. I scan the repo every 5 minutes to detect changes.

However, I do not want to be running builds and jobs automatically if it is some random feature branch. I am trying to limit the automatically triggered builds to only changes in staging and master branches.

So my question is, how/where do you configure Jenkins GitHub pipeline to only build on certain branches rather than scanning all branches?


Solution

  • A Multibranch pipeline job is your friend.

    Rather than trying to limit which branches Jenkins is polling firstly what I do in my Jenkinsfile is poll source control every minute:

    triggers { pollSCM('* * * * *') }
    

    This will poll every branch and create a job where it finds a Jenkinsfile in the location and name you specify in the Multibranch Pipeline job configuration.

    Side Note

    About the only configuration in a multibranch pipeline is:

    1. Where's the SCM repo?
    2. Workspace relative path and name of Jenkinsfile. (You can call it Bob if you want)

    A multibranch pipeline job sets an additional environment variable: BRANCH_NAME which allows you to conditionally perform actions in pipeline like so:

    script {
        if( "${env.BRANCH_NAME}" == "integration" ) {
            //Do something useful
        }
    }
    

    Using this method you can also decide to do nothing in response to a poll event.