Jenkins pipeline get other jobs status by curl
Requirement
- We have job_A, job_B & job_C
- Whenever job_B or job_C is built (all cases of Success or Failure or Unstable), job_A will be triggered automatically
- Job_A will get its upstream job status bu Jenkins API
Solution
- Go to your Jenkins Credentials (like http://localhost:8080/credentials/store/system/domain/_/newCredentials) and create a "Username and Password" kind credential with ID as MY_TOKEN
- Install jq & curl onto the agent machine. Ubuntu can use "sudo apt-get install jq curl"
- Jenkins pipeline (scripted type)
properties([
parameters([
string( name: 'NODE_LABEL', defaultValue: 'my_node',
description: 'Agent to run this job, should have curl and jq installed', trim: true),
booleanParam(name: 'DELETE_WS', defaultValue: true,
description: 'Delete workspace before operation, to ensure clean results'),
string( name: 'JENKINS_URL', defaultValue: 'http://localhost:8080',
description: 'JENKINS MASTER URL of upstream projects', trim: true),
string(name: 'UPSTREAMPROJECTS', defaultValue: 'job_B,job_C',
description: 'Build this project after one of these upstream projects built. Comma seperate.',
trim: true)
]),
buildDiscarder(logRotator(numToKeepStr: '100')),
pipelineTriggers([
upstream(upstreamProjects: params.UPSTREAMPROJECTS, threshold: 'FAILURE')
])
])
node(params.NODE_LABEL) {
dir(env.WORKSPACE.replaceAll('@.+', '')) {
catchError {
stage('Preparing workspace') {
if (params.DELETE_WS) {
deleteDir()
}
}
stage("Parse job info") {
def jobName = currentBuild.getBuildCauses()[0].upstreamProject
println jonName
def buildNumber = currentBuild.getBuildCauses()[0].upstreamBuild
println buildNumber
def upstreamUrl = currentBuild.getBuildCauses()[0].upstreamUrl
println upstreamUrl
final String buildURL = "${params.JENKINS_URL}/${upstreamUrl}${buildNumber}"
println buildURL
final String URL = "${params.JENKINS_URL}/${upstreamUrl}${buildNumber}/api/json"
env.ENVURL = URL
withCredentials([usernameColonPassword(credentialsId: 'MY_TOKEN',
variable: 'TOKEN')]) {
final def (String response, int code) =
sh(script: '''
unset https_proxy
unset http_proxy
curl -s -w '\\n%{response_code}' -u ${TOKEN} ${ENVURL}
'''
, returnStdout: true)
.trim()
.tokenize("n")
echo "HTTP response status code: $code"
if (code == 200) {
sh(script: "echo '$response' > response.json", returnStdout: true)
def buildDuration = sh(script: "jq -r '.duration' response.json",
returnStdout: true).trim()
buildDuration = buildDuration.toInteger()/(3600000)
println buildDuration
def buildDateMili = sh(script: "jq -r '.timestamp' response.json",
returnStdout: true).trim()
def buildDate = new Date(buildDateMili as long).format("yyyy-MM-dd HH:mm")
println buildDate
def buildStatus = sh(script: "jq -r '.result' response.json",
returnStdout: true).trim()
print buildStatus
}
}
}
}
}
}
Loading