Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a Jenkins Pipeline on Git commit

I'm setting up Jenkins pipeline for my .Net Core application.

Jenkins multibranch pipeline build gets trigger on Git commit if I am configuring the checkout SCM in multibranch Pipeline configuration. But multibranch Pipeline build is not getting trigger on git commit if I checkout SCM explicitly inside Jenkins Declarative Pipeline script.

Is there any way to resolve this issue?

Below is the checkout command which I am using inside the script:

checkout([$class: 'GitSCM', branches: [], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CleanCheckout'], [$class: 'PruneStaleBranch']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'credential-id', url: 'my/git/ssh/url']]])
like image 869
Lets_Find Avatar asked Feb 14 '19 08:02

Lets_Find


1 Answers

To get the build triggered on new git commit you should first enable SCM polling in your pipeline script by adding proper triggers directive to your Jenkinsfile:

triggers {
  pollSCM 'H/2 * * * *'
}

This will poll your SCM for any changes every two minutes. If a change is detected since the last build your job will be triggered to build the changes.

Polling is the easiest way to get what you want. However, you should consider using post-commit hook instead of polling. Using polling Jenkins has to periodically check SCM for the changes. In case of post-commit hook, Jenkins will be notified about the changes by SCM if necessary. It's prefered over polling because it will relieve the number of required requests and the traffic from Jenkins towards SCM repository.

After configuring post-commit hook, the triggers directive should be modified by providing an empty string as cron parameter to pollSCM trigger.

triggers {
  pollSCM ''
}

It can be confusing but this empty string is required to enable post-commit hooks requests to be handled by the job. It's also not very well documented by Jenkins docs.

like image 182
Marcin Kłopotek Avatar answered Oct 07 '22 06:10

Marcin Kłopotek