How-To: Trigger Jenkins Builds Through Bitbucket Server

I'll make this quick: First, install the following Jenkins plugins:

Add the following trigger to your Jenkinsfile (I use the declarative style):

pipeline {
    triggers {
        GenericTrigger(
            // these values are extracted from the webhook request body by JsonPath
            genericVariables: [
                [key: 'commit', value: '$.changes[0].toHash'],
                [key: 'author', value: '$.actor.displayName'],
                [key: 'branch', value: '$.changes[0].ref.displayId']
            ],

            causeString: 'Triggered by Bitbucket Webhook on commit $commit by $author',

            token: 'my-project-token',

            printContributedVariables: true, // this helps debugging the trigger
            printPostContent: true,

            silentResponse: false,

            regexpFilterText: "\$branch",
            regexpFilterExpression: BRANCH_NAME
        )
    }
    // ...
}

In Bitbucket go to Repository settings > Webhook and add a new webhook. Enter the URL <JENKINS_URL>/generic-webhook-trigger/invoke?toekn=<TOKEN>. Replace <JENKINS_URL> and <TOKEN> with their respective values (my-project-token in the example Jenkinsfile above). Make sure the checkbox "Push" is checked, click "Save" and you should be done. Next time you push to your repo Jenkins should automatically start a build.

To keep Bitbucket up-to-date about the build status, add notifyBitbucket() calls to the start and end of your Jenkinsfile. The exact command is best generated by the Pipeline Syntax tool inside Jenkins itself, available on your Jenkins job page.

Show Comments