Get BuildStatus from triggered Freestyle Job - jenkins

I use something like the following code to trigger multiple Freestyle Jobs inside my Jenkins Job
[...]
stage('build') {
try{
parallel(
build1: {
def buildJob1 = build job: build1, parameters:[string(name: 'CPNUM_PARAM', value: CPNUM_PARAM)]
buildJob1BuildNum = buildJob1.getNumber().toString()
},
build2: {
def buildJob2 = build job: build2, parameters[string(name: 'CPNUM_PARAM', value: CPNUM_PARAM)]
buildJob1BuildNum = buildJob1.getNumber().toString()
},
failFast: false
)
} catch (e){
[...]
}
}
[...]
The line buildJob#BuildNum = buildJob#.getNumber().toString() allows me to retrieve the BuildNumber of the triggered job.
Now I am searching for a way to retrieve the Buildstatus (success/unstable/failed) But I cant find anything.
I tried:
buildJob#BuildStatus = buildJob#.getStatus().toString()
buildJob#BuildStatus = buildJob#.getBuildStatus().toString()
etc. but none of them are working. I also failed to find some informations on the web.

I figured it out:
buildStatus = buildJob1.getResult().toString()
works fin for me

Related

How to get Jenkins build status without running build

How can I get the status of already completed builds?
The code below starts the build, but I just need to know the build status by name.
I need to find out the names of the failed builds in order to send the data in one message to the mail.
Map buildResults = [:]
Boolean failedJobs = false
void nofify_email(Map results) {
echo "TEST SIMULATE notify: ${results.toString()}"
}
Boolean buildJob(String jobName, Map results) {
def jobBuild = **build job: jobName**, propagate: false
def jobResult = jobBuild.getResult()
echo "Build of '${jobName}' returned result: ${jobResult}"
results[jobName] = jobResult
return jobResult == 'SUCCESS'
}
pipeline {
agent any
stages {
stage('Parallel Builds') {
steps {
parallel(
"testJob1": {
script {
if (!buildJob('testJob1', buildResults)) {
failedJobs = true
}
}
},
)
}
}
I couldn't find anything to replace build job

Jenkins Pipeline - build same job multiple times in parallel

I am trying to create a pipeline in Jenkins which triggers same job multiple times in different node(agents).
I have "Create_Invoice" job Jenkins, configured : (Execute Concurrent builds if necessary)
If I click on Build 10 times it will run 10 times in different (available) agents/nodes.
Instead of me clicking 10 times, I want to create a parallel pipeline.
I created something like below - it triggers the job but only once.
What Am I missing or is it even possible to trigger same test more than once at the same time from pipeline?
Thank you in advance
node {
def notifyBuild = { String buildStatus ->
// build status of null means successful
buildStatus = buildStatus ?: 'SUCCESSFUL'
// Default values
def tasks = [:]
try {
tasks["Test-1"] = {
stage ("Test-1") {
b = build(job: "Create_Invoice", propagate: false).result
}
}
tasks["Test-2"] = {
stage ("Test-2") {
b = build(job: "Create_Invoice", propagate: false).result
}
}
parallel tasks
} catch (e) {
// If there was an exception thrown, the build failed
currentBuild.result = "FAILED"
throw e
}
finally {
notifyBuild(currentBuild.result)
}
}
}
I had the same problem and solved it by passing different parameters to the same job. You should add parameters to your build steps, although you obviously don't need them. For example, I added a string parameter.
tasks["Test-1"] = {
stage ("Test-1") {
b = build(job: "Create_Invoice", parameters: [string(name: "PARAM", value: "1")], propagate: false).result
}
}
tasks["Test-2"] = {
stage ("Test-2") {
b = build(job: "Create_Invoice", parameters: [string(name: "PARAM", value: "2")], propagate: false).result
}
}
As long as the same parameters or no parameters are passed to the same job, the job is only tirggered once.
See also this Jenkins issue, it describes the same problem:
https://issues.jenkins.io/browse/JENKINS-55748
I think you have to switch to Declarative pipeline instead of Scripted pipeline.
Declarative pipeline has parallel stages support which is your goal:
https://www.jenkins.io/blog/2017/09/25/declarative-1/
This example will grab the available agent from the Jenkins and iterate and run the pipeline in all the active agents.
with this approach, you no need to invoke this job from an upstream job many time to build on a different agent. This Job itself will manage everything and run all the stages define in all the online node.
jenkins.model.Jenkins.instance.computers.each { c ->
if(c.node.toComputer().online) {
node(c.node.labelString) {
stage('steps-one') {
echo "Hello from Steps One"
}
stage('stage-two') {
echo "Hello from Steps Two"
}
}
} else {
println "SKIP ${c.node.labelString} Because the status is : ${c.node.toComputer().online} "
}
}

killing/stopping Jenkins job with a very long list

I'm new to Jenkins so I hope my terms are correct:
I have a Jenkins job that triggers another job. This second job tests a very long list of items (maybe 2000) it gets from the trigger.
Because it's such a long list, I pass it to the second job in groups of 20.
Unfortunately, this list turned out to take an extremely long time, and I can't stop it.
No matter what I tried, stop/kill only stop the current group of 20, and proceeds to the group.
Waiting for it to finish, or doing this manually for each group is not an option.
I guess the entire list was already passed to the second job, and it's loading the next group whenever the current one ends.
What I tried:
Clicking the "stop" button next to the build on the trigger and the second job
Using purge build queue add on
Using the following script in script console:
def jobname = "Trigger Job"
def buildnum = 123
def job = Jenkins.instance.getItemByFullName(jobname)
for (build in job.builds) {
if (buildnum == build.getNumber().toInteger()){
if (build.isBuilding()){
build.doStop();
build.doKill();
}
}
}
Using the following script in script console:
String job = 'Job name';
List<Integer> build_list = [];
def result = jenkins.model.Jenkins.instance.getItem(job).getBuilds().findAll{
it.isBuilding() == true && (!build_list || build_list.contains(it.id.toInteger()))}.each{it.doStop()}.collect{it.id};
println new groovy.json.JsonBuilder(result).toPrettyString(); ```
This is my groovy part of the code that splits it into groups of 20. Maybe I should put the parallel part outside the sub list loop?
Is there a better way to divide into sub lists for future use?
stages {
stage('Execute tests') {
steps {
script {
// Limit number of items to run
def shortList = IDs.take(IDs.size()) // For testing purpose, can be removed if not needed
println(Arrays.toString(shortList))
// devide the list of items into small, equal,sub-lists
def colList = shortList.toList().collate(20)
for (subList in colList) {
testStepsForParallel = subList.collectEntries {
["Testing on ${it}": {
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
stage(it) {
def buildWrapper = build job: "Job name",
parameters: [
string(name: 'param1', value: it.trim()),
string(name: 'param2', value: "")
],
propagate: false
remoteBuildResult = buildWrapper.result
println("Remote build results: ${remoteBuildResult}")
if (remoteBuildResult == "FAILURE") {
currentBuild.result = "FAILURE"
}
catchError(stageResult: 'UNSTABLE') {
copyArtifacts projectName: "Job name", selector: specific("${buildWrapper.number}")
}
}
}
}]
}
parallel testStepsForParallel
}
}
}
}
}
Thanks for your help!
Don't know what else to do to stop this run.

jenkins pipeline catch build_job info for a failed parallel build

Does anyone know how to catch the failed job's number in a parallel pipeline execution while still have failFast feature working for short-circuiting of builds in the event of a job failure? I know i can kind-of make it work if i do "propagate = false" while running the build step but that kills the failFast feature, and i need that.
For example, below is my code and i want the value of variable achild_job_info inside the catch block as well.
build_jobs = [“Build_A”, “ Build_B”, “ Build_C”]
def build_job_to_number_mappings = [:]
// in this hashmap we'll place the jobs that we wish to run
def branches = [:]
def achild_job_info = ""
def abuild_number = ""
for (x in build_jobs) {
def abuild = x
branches[abuild] = {
stage(abuild){
retry(2) {
try {
achild_job_info = build job: abuild
echo “ achild_job_info” // —> this gives: org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper#232601dc
abuild_number = achild_job_info.getId()
build_job_to_number_mappings[abuild] = achild_job_info.getNumber()
} catch (err) {
echo “ achild_job_info: ${achild_job_info } “ // —> This comes empty. I want the runwrapper here as well, just like in the try block.
abuild_job_number = abuild_job_info.getId()
build_job_to_number_mappings[abuild] = achild_job_info.getNumber()
} // try-catch
} // stage
} // branches
} // for
branches.failFast = true
parallel branches
The only way i could find out for now is to use the value of the 'exception string' and split it to get the current build number and name. I am not sure that is the most robust way to do this but works for now. Posting this reply to help others.
You need to avoid throwing by turning off the exception propagation:
achild_job_info = build job: abuild, propagate: false
if(achild_job_info.result == "SUCCESS") { ...
P.S. A little late, but I just got here looking for this myself.

Get the build number of a failed build in a parallel build in jenkins workflow

I am executing 3 parallel jobs, each that run tests, from my job as follows:
def run_job(job) {
output = build(job:job, parameters:parameters)
def buildNumber = output.getNumber().toString()
test_results[job] = '/job/'+ job +'/' + buildNumber + '/artifact/test_result.xml'
}
def test_func_array = [:]
def test_results = [:]
test_func_array['Python_Tests'] = {run_job('Run_Python_Tests', test_results)}
test_func_array['JS_Tests'] = {run_job('Run_JS_Tests', test_results)}
test_func_array['Selenium_Tests'] = {run_job('Run_Selenium_Tests', test_results)}
parallel(test_func_array)
I am able to get the build number using the output.getNumber() call when each job succeeds. However, when a job fails, build() function call throws an exception so I cannot get the build number.
However, failed builds can still have build numbers and have archived artifacts.
How do I get the build number of a failed build?
if you use propagate: false, you can't use try-catch block because build job don't throw exception when the job failed so you need to handle the result by getResult() method like this:
stage('build something'){
def job_info = build job: build_something, propagate: false,
println "Build number: ${job_info.getNumber()}"
currentBuild.result = job_info.getResult()
}
see also: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/
Use propagate: false. See Snippet Generator for details.
I think Jesse's answer is valid when you want to complete all the parallel jobs, even when one of more jobs have failed. So basically, it will disable the failFast feature.
Does anyone know how to catch the failed job's number while still have failFast feature working to short-circuit the builds in the event of a job failure? For example, below is my code and i want the value of variable achild_job_info inside the catch block as well.
build_jobs = [“Build_A”, “ Build_B”, “ Build_C”]
// in this hashmap we'll place the jobs that we wish to run
def branches = [:]
def achild_job_info = ""
def abuild_number = ""
for (x in build_jobs) {
def abuild = x
branches[abuild] = {
stage(abuild){
def allow_retry = true
retry(2) {
try {
achild_job_info = build job: abuild
echo “ achild_job_info” // —> this gives: org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper#232601dc
abuild_number = achild_job_info.getId()
build_job_to_number_mappings[abuild] = achild_job_info.getNumber()
} catch (err) {
echo “ achild_job_info: ${achild_job_info } “ // —> This comes empty. I want the runwrapper here as well, just like in the try block.
abuild_job_number = abuild_job_info.getId()
build_job_to_number_mappings[abuild] = achild_job_info.getNumber()
} // try-catch
} // stage
} // branches
} // for
branches.failFast = true
parallel branches

Resources