Jenkins remote build trigger with Bitbucket hook

  15 Nov 2014

To use remote build trigger, there two types of token that we need:

  1. The user API token.
  2. The project token.

To get user API token, we need to go to jenkins user configuration page, i.e. http://{jenkins_hostname}/user/{username}/configure then click on “Show API Token”. that we will treat this token as password for the user.

And the project’s token we need to go to the job configuration, i.e. http://{your-jenkins-ci}/job/{job-name}/configure Look at “build triggers” and just enable “Trigger builds remotely (e.g., from scripts)” you can enter some random alphanumeric string as token in Authentication Token. ( or, use command like: cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w ${1:-32} | head -n 1 )

After we got these two tokens, we can test the hook manually.

How to test?

If the Prevent Cross Site Request Forgery option in your Jenkins is disabled, use curl command like so:

curl -u {username}:{userAPItoken} -X POST http://{jenkins_hostname}{/prefix_if_you_have}/job/{project_name}/build?token={project_token}

Check the log in /var/log/jenkins/jenkins.log or see if there is new build.

But, if that is enabled. You have to send a CSRF protection token as an HTTP request header. In order to do that, you have to request to this endpoint to retrive that information beforehand, like so:

curl -u {username}:{userAPItoken} http://{jenkins_hostname}{/prefix_if_you_have}/crumbIssuer/api/json

And you will get json response:


After that, get crumbRequestField and crumb values from the response, put it in a format “.crumb:abcd5577dd”, it is what you should add to the subsequent request header, like so:

curl -u {username}:{userAPItoken} -H ".crumb:abcd5577dd" -X POST {jenkins_hostname}/{prefix_if_you_have}/job/{job_name}/build?token={your_random_token}

It should also trigger new build like when you disable csrf.

And, we can now configure hook in bitbucket. Go to repository admin page. In Integrations section, click Hook ( i.e.{username}/{project}/admin/hooks ) Select Jenkins hook and Add hook, then configure it like so:

Csrf Enabled: checked only if you have enabled the Prevent Cross Site Request Forgery exploits in Jenkins
Endpoint: http://{username}:{The user API token}@{jenkins_hostname}/{prefix_if_you_have}
Module name: (Leave this blank)
Project name: The job name
Token: The project token

Now every new commit to Bitbucket should trigger a new build in Jenkins succesfully!

comments powered by Disqus