API

Webhook to Jenkins hook settings can be updated via the Atlassian Bitbucket API via the following endpoint:

/rest/api/latest/projects/{0}/repos/{1}/settings/hooks/com.nerdwin15.stash-stash-webhook-jenkins:jenkinsPostReceiveHook/enabled
JAVA

For more on the Bitbucket REST API for updating and changing hooks, you can read here.

We've created a sample python script which updates the settings for you. It reads in a settings.json file which you can download here or below.

If you'd like to change the webhook source, you can add jenkinsEndPointType to the json setting with one of the following values:

Bitbucket Branch Source Plugin

com.nerdwin15.stash.webhook.notifier.BitbucketSourceNotifier

Git Plugin

com.nerdwin15.stash.webhook.notifier.GitPluginNotifier

Example Scripts

Example of script for initial configuration


configure-webhook-jenkins.py
#!/usr/bin/python
import httplib
import sys
import json
import argparse
from urlparse import urlparse
from base64 import b64encode

parser = argparse.ArgumentParser(description='Sample script to update Webhook To Bitbucket settings examples.')
parser.add_argument('--bitbucket_url', type=str, help='Url for Bitbucket instance.',
                    default='http://localhost:7990/bitbucket')
parser.add_argument('--username', type=str, help='Username for user with access to repository',
                    default='admin')
parser.add_argument('--password', type=str, help='Password for user with access to repository',
                    default='admin')
parser.add_argument('--project', type=str, help='Project key where repository is located',
                    default='PROJECT_1')
parser.add_argument('--repository', type=str, help='Repository key for the instance',
                    default='rep_1')
parser.add_argument('--settings', type=str, help='Path to the settings file. JSON formatted.',
                    default='settings.json')
args = parser.parse_args()

bb_url = args.bitbucket_url
username = args.username
password = args.password
project_key = args.project
repository_slug = args.repository
settings_path = args.settings

end_point = "/rest/api/latest/projects/{0}/repos/{1}/settings/hooks/com.nerdwin15.stash-stash-webhook-jenkins" \
            "%3AjenkinsPostReceiveHook/enabled".format(project_key, repository_slug)

settings_file = open(settings_path, 'r')
try:

    settings = settings_file.read()
    try:
        j = json.loads(settings)  # just to validate
    except:
        print "Invalid JSON: %s" % settings
        sys.exit(1)
finally:
    settings_file.close()

url_obj = urlparse(bb_url)

headers = {
    'authorization': "Basic " + b64encode(username + ':' + password),
    'Content-Type': 'application/json'
}

connection = httplib.HTTPConnection(url_obj.hostname, url_obj.port)

try:
    connection.request("PUT", url_obj.path + end_point, body=settings, headers=headers)
    r1 = connection.getresponse()

    print r1.status, r1.reason, r1.getheaders()

    data1 = r1.read()
    print data1
finally:
    connection.close()
PY


settings.json
{
    "branchOptions": "whitelist", 
    "branchOptionsBranches": "master, develop, feature-1", 
    "cloneType": "custom", 
    "cloneType2": "custom", 
    "gitRepoUrl": "http://172.17.0.1:7990/bitbucket/scm/project_1/rep_1.git",
    "gitRepoUrl2": "http://172.17.0.1:7990/bitbucket/scm/project_1/rep_1.git",
    "ignoreCommitters": "admin, user", 
    "jenkinsBase": "http://localhost:8080",
    "jenkinsBase2": "https://localhost:8083",
    "ignoreCerts": false,
    "omitHashCode": false,
    "omitBranchName": false,
    "omitTriggerBuildButton": false
}
JSON



Example of script to modify settings


#!/usr/bin/python
import requests
import string
import json


def get_projects(s):
    projects = []
    limit = 5
    start = 0
    is_last_page = False

    while not is_last_page:
        s.headers.update({'Content-Type': 'application/json'})
        r = s.get('{}/rest/api/1.0/projects?limit={}&start={}'.format(bitbucket_url, limit, start))
        data = r.json()
        is_last_page = data['isLastPage']
        if 'nextPageStart' in data:
            start = data['nextPageStart']
        
        for project in data['values']:
            projects.append(project['key'])

    return projects

def get_hook_settings(s, project_key):
    r = s.get((hook_api + '/settings').format(bitbucket_url, project_key))

    return r.json();

def update_hook_settings(s, project_key, config):
    r = s.put((hook_api + '/enabled').format(bitbucket_url, project_key), json = config)

    print r.status_code
    print r.text



bitbucket_url = "http://localhost:7990/bitbucket"
hook_api = "{}/rest/api/latest/projects/{}/settings/hooks/com.nerdwin15.stash-stash-webhook-jenkins%3AjenkinsPostReceiveHook"
username = "admin"
password = "admin"

s = requests.Session()
s.auth = (username, password)
s.headers.update({'X-Atlassian-Token':'nocheck'})
s.headers.update({'Content-Type': 'application/json'})

for project in get_projects(s):
    config = get_hook_settings(s, project)
    config['jenkinsBase']='http://localhost:8080/jenkins'
    
    update_hook_settings(s, project, config)
PY



Parameter details

disabledEvents is a comma-separated list of class names of events to ignore. Supported class names are listed below, with links to the corresponding Bitbucket documentation explaining when each event is triggered: