12
votes

I have a Jenkins job (multibranch pipeline) setup for a GitHub repo. I want to trigger that job automatically whenever there is a change pushed to that Git repo. How can I achieve this using a Jenkinsfile?

I want to avoid any config change in the Jenkins job such as Poll SCM etc. For multibranch pipeline there is no such option as Build whenever a change is pushed to GitHub

3
this is what should happen if you configure your mbp. Add your source (git) and fill in the repo endpoint. Make sure there is a Jenkinsfile at root level and set build configuration > mode to by Jenkinsfile. Then make sure that github trigegrs jenkins (via project > settings > services > Jenkins (github plugin)) - Rik
@Rik Unfortunately this does not seem to be working. I have covered all the points you mentioned. This worked when I added poll scm option but that's what I want to avoid. Just to add one more detail - I am using Jenkins Enterprise and we have a folder there to create jobs related to our team. - Saikat
at my work we have this configured for gitlab, and that works. I assume github is the same. If I have Some time later today I will check if I can get it working for github and then post a screenshot - Rik
Thanks for your help @Rik, much appreciated! - Saikat
If I use the Git (not Github) plugin, it works config and branch-index - Rik

3 Answers

6
votes

For your job "reacting" to events from your GitHub, set the job build trigger to "Poll SCM", but do not specify a schedule, as described on this Stackoverflow answer.

For declarative Jenkinsfile, this means:

pipeline {
  triggers {
    pollSCM('') // Enabling being build on Push
  }
  ...
}

Further readings:

3
votes

You can use this descriptive pipeline script to auto build your pipeline whenever new changes are pushed to github

pipeline{
   agent any     
     triggers {
        githubPush()
      }
   ...
 }

Also you should enable the github webhook with relavant secret tokens.

2
votes

The easiest option by far (that I'm aware of) is to remotely tell the Jenkins Git plugin that there's a new commit for a defined repository. However, this will not trigger Jenkins to start a job immediately. What happens is that the Git plugin starts (re-)indexing the specific repository. If changes are detected the Jenkins job is then started.

From your repository (GitHub, GitLab, etc.) you should trigger the following URL:

http://my-jenkins-host/git/[email protected]:group/repository.git&delay=0sec

The value for url must match the SCM URL you configured in the Jenkins job (Git plugin)!

Gotcha: it may be that your Jenkins is not deployed under the root context (/) in which case the URL would be http://my-jenkins-host/context-path/git/...