Parameters added to build in the fly not passed to downstream jobs - jenkins

I have Job_1, and Job_2.
In Job_1,
Step 1: Execute system Groovy script
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
Step 2: Trigger/call builds on other projects
Projects to build: JOB_2
Add parameters: Current build parameters
Step 3:
Execute Windows batch command
echo arts = %ARTS%
In Job_2,
Step 1:
Execute Windows batch command
echo arts from Job_1 = %ARTS%
Build Job_1, it does print out:
arts = safsaf
build_2 was successfully triggered, and print out:
arts from Job_1 = (blank)
it appears that only parameters in Job_1 defined in the This build is parameterized section can be passed to the downstream projects.
is this the expected behavior? How can parameters added in the fly be passed along?

I tried and this works:
in Job_1,
define a string parameter "ARTS" in the This build is parameterized section,
and change Groovy script from
import hudson.model.*
def build = Thread.currentThread().executable
def param = []
param.add(new StringParameterValue('ARTS', "safsaf"))
def pa = new ParametersAction (param)
build.addAction(pa)
to
import hudson.model.*
def build = Thread.currentThread().executable
build.replaceAction(
new ParametersAction(
new StringParameterValue('ARTS', 'safsaf')))
to overwrite the value of "ARTS", instead of adding a new parameter.

Give Parameterized Trigger Plugin a try. My downstream job was kicked off by a post build step Trigger parameterized build on other projects with Current build parameter from the plugin instead of the regular downstream job. Anything defined in This build is parameterized in Job_2 would pick up parameters passed from Job_1.
I may not be using this absolutely correct and I think there is a limitation on what can be captured vs cannot, but so far this captures all desired parameter from Job_1 for me.

Related

How to get latest build number from another job in jenkins pipeline

I am using jenkins pipeline 2.0, and I would like to get another job's latest successful build number.
What's the pipeline syntax to use?
You can get it this way
def buildNumber = Jenkins.instance.getItem('jobName').lastSuccessfulBuild.number
If you get a RejectedAccessException you will have to approve those methods, see In-process Script Approval
To add to Vitalii's answer, this is in case you're using Multibranch Pipeline Plugin:
def buildNumber = Jenkins.instance.getItem('jobName').getItem('branchName').lastSuccessfulBuild.number
It's so annoying to get approvals in enterprise environment(a lot of request and approvals)
So I am using following API way to get the latest build number.
import groovy.json.JsonSlurperClassic
httpRequest url: 'https://jenkinsurl.local/job/Build/api/json', outputFile: 'output.json'
def jsonFile = readFile(file: 'output.json')
def data = new JsonSlurperClassic().parseText(jsonFile)
latestBuildNumber = "${data.lastSuccessfulBuild.number}"
def build_job = build job: "Build"
build_job_number = build_job.getNumber()

Jenkins - How to list build choices from successful builds of another project

Assume I have two projects build and deploy.
I expect the build parameters of deploy to be a dropdown so that I can select which one to deploy.
All the dropdown items are build names of successful builds in build.
Actually I have found this through Groovy scripts before, but I cannot find them now. :(
This groovy script ,when added in an Extensible Choice parameter, can list out the successful builds from a given job.
def builds = []
def job = jenkins.model.Jenkins.instance.getItem(JOB-NAME)
job.builds.each {
def build = it
if (it.getResult().toString().equals("SUCCESS")) {
it.badgeActions.each {
builds.add(build.displayName[1..-1])
}
}
}
builds.unique();

Mark Jenkins Pipeline as Promoted

Last I knew, Jenkins Pipelines did not support promotions, so to work around this, I created a job called "job-name-promotion" which would gather artifacts from the job I wanted to promote, and then mark the corresponding build as "Keep Forever." Is there a way to mark the build that was kept forever as "promoted" somehow? Preferably using one of the Stars that typically denote promotions? Or even better, is there a way to add Promotion Process steps to pipelines now?
Since it appears that pipelines still do not support promotions (as of 11/21/2017), I wrote a custom groovy script to iterate over all the jobs on the Jenkins server, locate the one we wish to promote and add a gold star to the corresponding build number:
import hudson.model.*
import jenkins.model.*
import org.jvnet.hudson.plugins.groovypostbuild.GroovyPostbuildAction
def log = manager.listener.logger
build = Thread.currentThread().executable
String jobName = build.project.getName()
// note: these two variables are defined as parameters of the current job
def number = manager.build.buildVariables.get("NUMBER") as int
def buildJobName = manager.build.buildVariables.get("BUILD_JOB_NAME")
Jenkins jenkins = Jenkins.getInstance()
List<Job> projects = jenkins.getAllItems(Job.class)
for (Job project : projects) {
if (project.getName().equals("platform-lanai-pipeline")) {
log.println("Found it!")
Run usb = project.getBuildByNumber(number)
usb.getActions().add(GroovyPostbuildAction.createBadge('star-gold.png', ''))
}
}

Access BUILD_NUMBER in Jenkins Promoted build plugin scripts

I am using Promoted Build plugin. And using some custom groovy scripts to validate the build! I wanted to access the value of BUILD_NUMBER from the groovy script. Can anyone suggest me how i can achieve this?
Another thing i am writing println statement in this groovy script but its no where getting logged. Any suggestion to debug the script flow how can i log the info ?
Thanks
If it's in runtime you can use:
def env = System.getenv()
//Print all the environment variables.
env.each{
println it
}
// You can also access the specific variable, say 'username', as show below
String user= env['USERNAME']
if it's in system groovy you can use:
// get current thread / Executor and current build
def thr = Thread.currentThread()
def build = thr?.executable
//Get from Env
def stashServer= build.parent.builds[0].properties.get("envVars").find {key, value -> key == 'ANY_ENVIRONMENT_PARAMETER' }
//Get from Job Params
def jobParam= "jobParamName"
def resolver = build.buildVariableResolver
def jobParamValue= resolver.resolve(jobParam)
Any println is sending output to the standard output steam, try looking at the console log.
Good luck!

How create Jenkins Build Pipeline depends on test result?

I have 3 Jenkins jobs. Smoke tests, critical path test (part 1), critical path test (part 2).
Now it starts one by one. I need create build PipeLine depends on test result. I need to take into account the results of a single test (#Test annotation in TestNG), ignoring the overall result of test suite.
I want to get the configuration like this:
Smoke tests -> If specified test passed then run critical path test Part 1 and Part 2 on different nodes
So, please tell me how depends in Jenkins only on one tests result (not all suite)?
You can try to use some of build log analysis plugins:
https://wiki.jenkins-ci.org/display/JENKINS/Text-finder+Plugin
https://wiki.jenkins-ci.org/display/JENKINS/Post+build+task
Scan build output, and downgrade build result to failure on specific text.
Next in downstream item check option "Build after other projects are built" in build triggers section. Set proper upstream item name and set proper trigger result.
I solved that task by using 2 Jenkins extensions:
https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
https://wiki.jenkins-ci.org/display/JENKINS/Build+Flow+Plugin
Create properties file from test. File contains property, that indicate result of test step status
With EnvInject Plugin add new step into Jenkins Job (step must be after test run) and inject parameter value (from file created at first step)
Create build flow with Build Flow Plugin
Write groovy script:
smokeTest = build( "Run_Smoke_Test" )
def isTestStepSuccessful = smokeTest.environment.get( "TestStepSuccessful" )
if (isTestStepSuccessful != "false") {
parallel (
{
build("Run_Critical_Path_Part_1_Test")
build("Run_Critical_Path_Part_3_Test")
},
{
build("Run_Critical_Path_Part_2_Test")
}
)
}
build( "Run_Critical_Path_Final_Test" )

Resources