Trigger Jenkins multibranch pipeline with curl or webhook
Git branch source
Jenkins jobs that use the widely used git plugin, can be triggered remotely with curl or a webhook. The job must have the option “Poll SCM” enabled. That’s all to enable push triggers, no timer has to be configured. Jobs are only executed if there is an actual source code change. Off course you can configure a timer, if you also want a periodic pull.
An example curl commando to trigger all jobs that have configured the repository URL “ssh://git@bitbucket.mycompany.example/demo/my-api.git” in Git SCM and have “Poll SCM” enabled:
curl 'http://jenkins.mycompany.example/git/notifyCommit?url=ssh://git@bitbucket.mycompany.example/demo/my-api.git' --user 'jenkins-trigger:mysecrettoken123'
Note that “mysecrettoken123″ is not the password of the “jenkins-trigger” user I created, but is an API token. This can be generated on the configuration page (/user/jenkins-trigger/configure) of the user.
Multibranch pipelines have the link “Scan Multibranch Pipeline Now“. I was searching the internet for how to do this with an API call, curl or a webhook. I was surprised that it was so hard to find a good solution. A lot of old dated, unclean solutions can be found.
But once again, the “/git/notifyCommit” endpoint comes to the rescue! If the repository above is configured in the multibranch pipeline job, then the very same curl command can be used! Multibranch pipelines don’t have a “Poll SCM” option, so that step can be skipped. You will probably get the following output this time:
“No git jobs using repository”. But that is a false message for multibranch pipelines. If you open the multibranch job you will see that only the branch you made a change in, will be executed just after you executed the curl command!
Bitbucket branch source plugin
The provided solution above only works with the generic Git branch source. The Bitbucket branch source plugin is not triggered by it, because it uses another endpoint “/bitbucket-scmsource-hook/notify”. Besides that, the endpoint must not only be triggered, but requires an actual payload. There is built-in support for Bitbucket cloud webhooks. For Bitbucket server, the Post Webhooks for Bitbucket add-on is recommended and well maintained.
If your Bitbucket Server / Stash is too old, the generic Git branch source can be a proper solution. One of the things that the Bitbucket branch source plugin does, is updating the build status per commit in Bitbucket. In order to achieve this with the generic Git branch source, you will need the Stash notifier plugin.