Skip to content

Instantly share code, notes, and snippets.

@blaffoy
Created July 3, 2017 14:04
Show Gist options
  • Select an option

  • Save blaffoy/d29170d95c3368cc58293d671bd2ca6c to your computer and use it in GitHub Desktop.

Select an option

Save blaffoy/d29170d95c3368cc58293d671bd2ca6c to your computer and use it in GitHub Desktop.
Jenkins system groovy script to push build status to GitHub
@Grapes(
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
)
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.JSON
import static groovyx.net.http.Method.POST
import hudson.model.Result
def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("envVars")
def git_commit = envVarsMap.get('GIT_COMMIT')
def node_name = envVarsMap.get('NODE_NAME')
def build_url = envVarsMap.get('BUILD_URL')
String git_url = envVarsMap.get('GIT_URL')
def github_auth_key = envVarsMap.get('GITHUB_AUTH_KEY')
def jenkins_github_status_map = [
(Result.SUCCESS): "success",
(Result.FAILURE): "failure",
(Result.UNSTABLE): "failure",
(Result.ABORTED): "error",
(Result.NOT_BUILT): "error"
]
Result jenkins_result = build.result
String github_result = (jenkins_result == null) ? 'pending' : jenkins_github_status_map[jenkins_result]
String desc = "Starting build on ${node_name}"
String target_url = "${build_url}"
def message = [
"state": github_result,
"target_url": target_url,
"description": desc,
"context": "continuous-integration/jenkins"
]
String repo_name = git_url.replaceAll("git@github.com:", '').replaceAll('.git', '')
String api_endpoint = "https://api.github.com/repos/${repo_name}/statuses/${git_commit}"
def http = new HTTPBuilder(api_endpoint)
http.request(POST, JSON) { req ->
headers.'Authorization' = "token ${github_auth_key}"
headers.'Content-Type' = 'application/json'
headers.'Accept' = 'application/vnd.github.v3+json'
headers.'User-Agent' = 'curl/7.51.0'
body = message
response.success = { resp, reader ->
println "$resp.statusLine Respond rec"
}
response.failure = { resp, json ->
print json
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment