For BitBucket status API notifications, we have the following workaround:
def obtainBitbucketToken() {
try {
echo "Obtaining BitBucket Access Token"
sh "curl -s -X POST https:${getBitbucketOAuthKey()}:${getBitbucketOAuthSecret()}\" -d grant_type=client_credentials | jsawk 'return this.access_token' | tr -d \"\\n\" > accessToken.txt"
def accessToken = readFile 'accessToken.txt'
echo "BitBucket Token request response: ${accessToken}"
return accessToken
} catch (error) {
echo "Failed to obtain BitBucket access token!"
return null
}
}
def notifyCommit(String accessToken, String commitHash, String repository, String buildKey, boolean inProgress, boolean runTests) {
echo "Notifying commit"
if (accessToken == null) {
echo "Failed to notify commit with null access token!"
return
}
try {
def state = null
def description = null
if (inProgress) {
state = 'INPROGRESS'
description = "Build in progress. Tests will run: ${runTests}"
} else {
if (currentBuild.result == 'SUCCESS') {
state = 'SUCCESSFUL'
if (runTests) {
description = 'Build has succeeded and all tests have passed!'
} else {
description = 'Build has succeeded but tests were not run!'
}
} else {
state = 'FAILED'
if (currentBuild.result == 'UNSTABLE') {
description = 'Build has succeeded, but some tests have failed!'
} else {
description = "Build has failed. Jenkins result is: ${currentBuild.result}"
}
}
}
def payload = "{\"state\": \"${state}\", \"key\": \"Jenkins ${buildKey}\", \"name\": \"Jenkins ${buildKey}\", \"url\": \"${env.BUILD_URL}\", \"description\": \"${description}\"}"
sh "curl -s -X POST https:Content-Type: application/json\" -H \"Authorization: Bearer ${accessToken}\" -d '${payload}'"
} catch(error) {
echo "There has been an error with notifying BitBucket!. Error: ${error}"
}
}
So, at the beginning of my pipeline script, after checkout and resolving of git commit, I call it this way:
def accessToken = obtainBitbucketToken()
notifyCommit(accessToken, commitHash, repository, keyPullRequestBuild, true, runTests)
After the build finishes, I just need to call:
def accessToken = obtainBitbucketToken()
notifyCommit(accessToken, commitHash, repository, keyPullRequestBuild, false, runTests)
This code needs to be run on unix node which has curl and jsawk tools installed (I tried JsonSlurper which should be built into the Groovy, but it kept crashing with serialization exceptions, even when used only from functions marked with @NonCPS).
We actually have solved this way: we created a webhook on BitBucket which every time there is a push to repository or pull request is created or updated, it calls this URL: http://jenkins.server/job/MyPipelineJob/build
MyPipelineJob is multibranch pipeline job which only enumerates changes in pull requests and feature branches and triggers builds if necessary. However, we are missing Build status badges from BitBucket BuildStatus API.