Generalized post webhook from scriptrunner for bitbucketto trigger builds on any ci tool

Devtools_Barclays August 28, 2017
We need a bit of guidance in creating a post commit webhook from bitbucket to trigger builds on ci tools . There are multiple ci tools such as teamcity ,Jenkins etc according to project setup.so we are trying to make a very generalized post commit webhook.

Just to explain the scenario:

---dev commits and pushes the code to bitbucket repo

---the post webhook will send the trigger event to ci tool(it can be any tool teamcity ,Jenkins,go etc)

--- once we get something on this , then we will script the trigger for other events as well such as pull requests, merges etc

1 answer

2 votes
Jonny Carter
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 29, 2017

The particulars will depend on each API that you use, but ScriptRunner comes bundled with the HttpBuilder library, which makes making HTTP requests of external APIs pretty straightforward.

Here's a pretty basic example that I used to contact a local jenkins instance.

import groovyx.net.http.ContentType
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method

if (repository.name == "myrepo") {
String jenkinsUrl = "http://localhost:8089/"
String userName = 'admin'
String password = 'admin'
String targetJob = 'job1'

def http = new HTTPBuilder(jenkinsUrl)
String uspass = "$userName:$password".bytes.encodeBase64()
http.setHeaders([Authorization: "Basic $uspass"])

def crumb
http.get(path: 'crumbIssuer/api/xml') { response, xml ->
crumb = xml.crumb.toString()
}
log.debug "Jenkins authorization crumb: $crumb"

http.headers += [
".crumb" : crumb, //different versions of Jenkins take different versions of this header
"Jenkins-Crumb": crumb
]

http.request(Method.POST, ContentType.TEXT) {
uri.path = "job/$targetJob/build"
query = [token: "62d07cb3d3571bebf23de309e88f1f3a6f7c93bd", crumb: crumb]
}
}

Naturally, you'll want to change the jenkinsUrl, repository name, target job name, and credentials used to match your use case. I'd also recommend that you store the jenkins credentials somewhere besides hard-coding them into your script (perhaps an environment variable or a credentials store on your server), then use the script to retrieve them.

I also assume that your Jenkins instance has CSRF protection enabled, since recent versions of Jenkins use it by default. If it's not enabled, you won't need the first get request to the crumbIssuer API, and you shouldn't need to set any authentication headers at all; the token should be sufficient to fire the Jenkins job.

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events