extract parameters from a jenkins previous build - jenkins

I am working on Jenkins version 2.32.1 pipeline. I want to extract the parameters that were chosen in the previous build of my job.
In our previous Jenkins instance ( 1.627 ) we were using jenkins.model.Jenkins.instance.getItem(job).lastBuild.getBuildVariables().get(param);
For some reason this is not working in this version (I also tried disabling the sandbox).
Any pointers on how to accomplish it?

Simplified version of the previous script:
def build = Jenkins.get().getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).find {it.displayName == 'YOUR_JOB_NAME_HERE'}?.getLastBuild()
build.actions.find{ it instanceof ParametersAction }?.parameters.each {echo "${it.name}=${it.value}"}
Actually a little bit shorter version for those who want to get the params for the current build from the previous run and is working on new 2+ Jenkins versions.
To get 1 particular parameter:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters.find{it.name == 'cls'}?.value
Get all params respectfully:
def cls = currentBuild.getPreviousBuild().getRawBuild().actions.find{ it instanceof ParametersAction }?.parameters

Something like this might work, based on https://stackoverflow.com/a/19564602/3920342:
def h = hudson.model.Hudson.instance
def r = null
h.getItems(org.jenkinsci.plugins.workflow.job.WorkflowJob).each {project ->
if (project.displayName.equals('YOUR_JOB_NAME')) {
r = project
}
}
r.getBuilds().findAll { b -> // here we loop over all past builds, apply some filter if necessary
def p = b?.actions.find{ it instanceof ParametersAction }?.parameters
p.each {
echo "parameter ${it.name}: ${it.value}"
}
}

For those who are not able to access getActions() due to admin permissions i.e. facing the following error:
Scripts not permitted to use method hudson.model.Actionable getActions
They can copy the parameter variables to the env and get them using build.previousBuild.buildVariables
stage('Prepare environment') {
steps {
script {
env.MY_PARAM_COPY = "${MY_PARAM}"
}
}
}
println("MY_PARAM in previous build: ${currentBuild.previousBuild.buildVariables["MY_PARAM_COPY"]}")

That's how I made it works, answer from #dan.goriaynov and #jherb caused some CPS closure issues for me.
(the gist of the code is to allow only greater TAG number than the previous one to be deployed)
stage('Validate build number') {
def previous_build = currentBuild.getPreviousBuild().getRawBuild();
def PREVIOUS_TAG = '';
for (int i = 0; i < previous_build.allActions.size(); i++) {
if (previous_build.allActions[i] in hudson.model.ParametersAction) {
PREVIOUS_TAG = previous_build.allActions[i].getParameter("TAG").value
}
}
if (PREVIOUS_TAG.toInteger() > TAG.toInteger()) {
echo PREVIOUS_TAG
error('TAG number needs to be greater than the previous one')
}
}

Related

How to list culprit users when Jenkins build fails (sending by Slack)

How I can list all culprits users related to the broken builds since the last successful build and the current one?
Besides that, how to compile all this information and then send by Slack?
The script below describes how to configure the post processing step to send culprits users from history of broken builds.
#!groovy​
pipeline {
agent { label 'pipeline-maven'}
post {
failure {
script {
def userDetailsService = load("get-users-details.groovy")
env.slack_msg = userDetailsService.getFailedBuildHistory()
}
slackSend baseUrl: 'https://xxx.slack.com/services/hooks/jenkins-ci/',
channel: '#xxxx',
color: 'bad',
token: 'aIPJis6V4P9VOpTFhUtCQRRL',
message: "Broken build ${currentBuild.fullDisplayName}\n${slack_msg}"
}
}
}
The script below (get-users-details.groovy) is responsible to enumerate all culprits based on the previous broken build history.
import jenkins.model.Jenkins
def String getFailedBuildHistory() {
def message = ""
// Iterate over previous broken builds to find culprits
def fullName = "pipeline-test"
def jobData = Jenkins.instance.getItemByFullName(fullName)
def lastStableBuild = jobData.getLastStableBuild()
def lastBuildNumber = jobData.getLastBuild().getNumber() - 1 // We subtract the current executing build from the list
if (lastStableBuild != null && lastStableBuild.getNumber() != lastBuildNumber) {
def culpritsSet = new HashSet();
message += "Responsibles:\n"
// From oldest to newest broken build, since the last sucessful build, find the culprits to notify them
// The list order represents who is more responsible to fix the build
for (int buildId = lastStableBuild.getNumber() + 1; buildId <= lastBuildNumber; buildId++) {
def lastBuildDetails = Jenkins.getInstance().getItemByFullName(fullName).getBuildByNumber(buildId)
if (lastBuildDetails != null) {
lastBuildDetails.getCulpritIds().each({ culprit ->
if (!culpritsSet.contains(culprit)) {
message += " ${culprit} (build ${lastBuildDetails.getNumber()})\n"
culpritsSet.add(culprit)
}
})
}
}
}
// Complement the message with information from the current executing build
if (currentBuild.getCurrentResult() != 'SUCCESS') {
def culprits = currentBuild.changeSets.collectMany({ it.toList().collect({ it.author }) }).unique()
if (culprits.isEmpty()) {
// If there is no change log, use the build executor user
def name = currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause').userName
message += " ${name} (current build ${currentBuild.getId()})"
} else {
// If there is change log, use the committer user
culprits.each({ culprit ->
message += " ${culprit} (current build ${currentBuild.getId()})"
})
}
}
return message
}
return [
getFailedBuildHistory: this.&getFailedBuildHistory
]

How to get number of failed builds by cause with Jenkins

I have the Build Failure Analyzer plugin installed in my Jenkins instance, and I have a number of different failures entered into the plugin. Does anyone know if it is possible to get the total number of failures across all jobs that have the same cause?
For example, I occasionally get "ChannelClosedException" failures if the build node goes offline during a build or test unexpectedly and I would like to determine how often this is happening across all my jobs. Is there some way to aggregate this value? I imagine it could be done through groovy if you can iterate over each build for each job and collect the Build Failure cause if one is detected.
Has anyone else done something like this before?
Not the exact answer... but should be able to modify to get what you are looking for:
Jenkins.instance.getAllItems(Job).each{
def jobBuilds=it.getBuilds()
//for each job get the things (you can limit at your convenience)
jobBuilds.each { build ->
def runningSince = groovy.time.TimeCategory.minus( new Date(), build.getTime() )
def currentStatus = build.buildStatusSummary.message
def cause = build.getCauses()[0] //we keep the first cause
def user = cause instanceof Cause.UserIdCause? cause.getUserId():""
println "Build: ${build} | Since: ${runningSince} | Status: ${currentStatus} | Cause: ${cause} | User: ${user}"
def parameters = build.getAction(ParametersAction)?.parameters
parameters.each {
println "Type: ${it.class} Name: ${it.name}, Value: ${it.dump()}"
}
}
}
Using some google-fu and some of the info from VinDev, I came up with this solution:
// get all jobs in Jenkins
Jenkins.instance.getAllItems(Job).each {
// get all builds for each job
def jobBuilds=it.getBuilds()
//for each build, get the name and status + and failure messages
jobBuilds.each { build ->
// get the build status
def currentStatus = build.buildStatusSummary.message
// we only care about the broken builds because we want failure messages
if (currentStatus.contains("broken")) {
println "Build: ${build} | Status: ${currentStatus}"
def BFA = build.actions.find{ it instanceof com.sonyericsson.jenkins.plugins.bfa.model.FailureCauseBuildAction };
if (BFA != null) {
for (failureCause in BFA.getFoundFailureCauses()) {
println("name: " + failureCause.getName() + ", description: " + failureCause.getDescription())
}
}
}
}
}

How to get list of individuals who broke the build in Jenkins Pipeline

Is there a way to retrieve a list of individuals who broke the build in Jenkins Pipeline, just like the mailer plugin apparently does to send out a mail to those involved?
I've found one possible way, though it is somewhat limited to the amount of builds that are being kept. By iterating over the previousBuild hierarchy and their change logs, this may be a solution:
def getAuthors(def build) {
def userIds = []
build.changeSets.each { hudson.scm.SubversionChangeLogSet changeLogSet ->
userIds += changeLogSet.collect { it.author.id }
}
userIds.unique()
}
def getIndividualsWhoBrokeTheBuild() {
def userIds = []
for(def build = currentBuild; build.result != 'SUCCESS'; build = build.previousBuild) {
userIds += getAuthors(build)
}
userIds.unique()
}
Suppose a job keeps only five builds, this won't return the original felon, if it was broken more than five builds before.

Jenkins Workflow Parallel step and closures

I'm trying to run a few suits with tests in parallel as a part of workflow. So I create a map, put there a couple of closures and pass it to parallel step. The issue that I'm facing related to name of the HTML report. After execution, I see a few identical "HTML Report" links, so I can't open specific report - all of them have the same name. I had tried to make this name unique, but these attempts were not successful. Does anyone faced similar thing?
def testExecutions = [:]
def testExecution = {
node {
//code to run tests
publishHTML(target: [allowMissing: false,
alwaysLinkToLastBuild: false,
keepAll: true, reportDir: 'target/reports',
reportFiles: 'index.html',
reportName: "HTML Report " + it)
}
}
for (int i = 0; i < 2; i++) {
final k = i
testExecutions.put("tests $k", {testExecution(k)})
}
parallel(testExecutions)
Maybe the testExecution() function lacks the it parameter?
def testExecution(it) = {
node {
....
}
}
It seems that your node is on the wrong level. Now this rises a really interesting question.
My guess would be that when your workers would actually get the node to execute k or it would have be already evaluated by the master, meaning that from the point of view of parallel call the closure implicit argument would always be equal to 1. (although I consider myself not educated enough with Jenkins workflow and groovy to say for sure)
This version should work for you
def testExecutions = [:]
def testExecution = {
println "HTML Report " + it
}
for (int i = 0; i < 2; i++) {
final k = i
testExecutions.put("tests $k", {node{testExecution(k)}})
}
parallel(testExecutions)

Jenkins Pipeline Execute Multiple FreeStyleProjects in Parallel [duplicate]

The script is not iterating through all the values of the 'modules' array.
class Module {
public String name = '';
public Boolean isCustom = false;
public Module(String name, Boolean custom){
this.name = name;
this.isCustom = custom;
}
}
//creates array from the ext_module env var
modules = [];
EXT_MODULE.split(',').each {
modules.add(new Module(it, false));
}
println modules;
modules.each {
println "MODULE NAME ::::: ${it.name}"
if(it.isCustom)
{
println "install custom";
} else {
println "install non custom";
}
};
This is the result of the run. The array shows 4 elements, but the code inside the .each black only executes once.
Running: Print Message
[Module#71f09325, Module#e1ddb41, Module#7069a674, Module#1f68f952]
Running: Print Message
MODULE NAME ::::: puppetlabs-ntp
Running: Print Message
install non custom
Running: End of Workflow
Finished: SUCCESS
The messages "Running: Print Message" and "Running: End of Workflow" indicate that you are using the new workflow plugin: https://wiki.jenkins-ci.org/display/JENKINS/Workflow+Plugin. This plugin currently has a bug causing at least some Groovy iterations involving a closure to be aborted after one iteration: https://issues.jenkins-ci.org/browse/JENKINS-26481
The workaround is to simply use an old school for loop (code below).
Also, NonCPS is another workaround.
There is an open issue for this matter. See here: https://issues.jenkins-ci.org/browse/JENKINS-26481
Update, Oct 24th, 2016
/**
* Dumps environment varibles to the log, using an old school for loop.
*/
import com.cloudbees.groovy.cps.NonCPS
def version = '1.0'
#NonCPS
def dumpEnvVars() {
def str = "Dumping build environment variables...\n"
for (Map.Entry<String, String> entry : currentBuild.build().environment) {
str += " ${entry.key} = ${entry.value}\n"
}
echo str
}
return this;
As of yesterday, the new Pipeline plugin was delivered in version 2.0 and correct this problem.
.each closures now work, but .collect still only iterate once.

Resources