Trigger build in Jenkins when git branches are created or deleted

Tobias picture Tobias · Sep 26, 2014 · Viewed 7.6k times · Source

I have a job in Jenkins for a project on GitHub, that I would like to be triggered whenever a new branch is created or an existing branch has been removed. Is this possible?

Notice: The Jenkins server is located internally in a company, so we can't use web hooks from GitHub.

Answer

Niels Bech Nielsen picture Niels Bech Nielsen · Sep 26, 2014

I can think of one approach, you may use.

Using Job DSL Plugin allow you to create or delete projects using Groovy. It is not hard to include github scanning and create jobs from that. Good thing about it is, that it recognizes deleted jobs as well.

I.e. Install Job DSL plugin, create a seed job (free-style) with a regular trigger, and paste something akin the below into your script..

def project = 'nbn/griffon-maven-plugin'
def branchApi = new URL("https://api.github.com/repos/${project}/branches")
def branches = new groovy.json.JsonSlurper().parse(branchApi.newReader())


branches.each { 
    def branchName = it.name
    job {
        name "${project}-${branchName}".replaceAll('/','-')
        scm {
            git("git://github.com/${project}.git", branchName)
        }
        steps {
            maven("test -Dproject.name=${project}/${branchName} ")
        }
    }
}