For BitBucket status API notifications, we have the following workaround:
def obtainBitbucketToken() {
try {
echo "Obtaining BitBucket Access Token"
sh "curl -s -X POST https://bitbucket.org/site/oauth2/access_token -u \"${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://api.bitbucket.org/2.0/repositories/microblink/${repository}/commit/${commitHash}/statuses/build -H \"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) // runTests is variable in my pipeline telling me whether tests should be run
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). |