I would like to dynamically generate my parameters on an input step from a loop inside my Jenkins pipeline.
This is my code:
var = input message: 'Tags a saisir', ok: 'Build!',
parameters: [
choice(name: 'name1', choices: file1),
choice(name: 'name2', choices: file2),
choice(name: 'name3', choices: file3),
choice(name: 'name4', choices: file4)
]
I would like to know if it is possible to generate each parameter from a loop like :
for (int i = 0; i < myList.size(); i++) {
theChoice = "choice(name : "+myList.get(i)+'choices: file"+i+")
}
and generate the input step from those lines.
Is that kind of approach possible ?
The main goal is to generate an input step with modular variables dependending on the jenkins file clone from the Git SCM
Regards,
Guillaume
You can do it like this
def parameterNames = fileMap.keySet().toList()
def choices = []
for (int i = 0; i < parameterNames.size(); i++) {
choices += choice(name : parameterNames[i], choices: fileMap[parameterNames[i]])
}
def var = input message: 'Tags a saisir', ok: 'Build!', parameters: choices
Where fileMap is a Map which contains possible choices fore each parameter name (key is a parameter name, value is a String of possible choices)
Related
I'm running the following code where the idea is to run as much "TestRunner" as possible during night. I've removed some unnecessary code if some variables aren't there the for easier reading.
I want to know each job if it was successful, aborted or failed and when I'm using parallel I'm not able to see it.
How can I modify my code so i can print each job state when its done? adding a variable is being wiped out to the last element in the for loop.
Thanks a lot
def numberOfRuns = 0
def availableExecutors = 5
def parallelRuns = [:]
// building executers for later use in parallel
for (int i = 0; i < availableExecutors; i++) {
parallelRuns[i] = {
waitUntil {
build job: 'TestRunner', parameters: [
string(name: 'randomBit', value: "${randomBit}"),
], propagate: false
numberOfRuns++
def now = new Date()
return (now > workDayMorning)
}
}
}
// Parallel stage - running al executers
parallel parallelRuns
I've tried to enter a variable to track job process, i tried to use the parallelRuns as object but didnt manage to get the result of each test passed or not.
A solution i've found is:
def Job = build job: 'TestRunner', parameters: [
string(name: 'randomBit', value: ${randomBit}")
], propagate: false
echo "Runner: ${Job.getDisplayName()} has ${Job.getResult()}
with duration: ${Job.getDuration()}"
This prints data of the job.
I have the following code as part of my declarative pipeline:
String CRON_SETTINGS = BRANCH_NAME ==~ /(master|.*release.*)/ ? '''30 23 * * * % param1=value1''' : ""
pipeline {
parameters {
choice(name: 'param1', choices: ['value1', 'value2'], description: 'param')
}
triggers {
parameterizedCron(CRON_SETTINGS)
}
}
Currently the Cron behaves in the following way:
every night at 23:30 PM a build of the job is built if my branch name is master or if it contains the string 'release', always with the value of param1 set to value1.
What I would like to achieve is this:
In case the barnch name is master, run the cron with value1 set to param1 parameter,
However, if the branch name contains 'release', then run the cron with value2 set to param1 parameter.
Would apprreciate your help to achieve this,
Thanks.
Late answer and I haven't tested this, but how about using a switch statement?
switch (BRANCH_NAME) {
case 'master':
cronSettings = '30 23 * * * % param1=value1'
break
case '.*release.*':
cronSettings = '30 23 * * * % param1=value2'
break
default:
cronSettings = ""
break
}
pipeline {
parameters {
choice(name: 'param1', choices: ['value1', 'value2'], description: 'param')
}
triggers {
parameterizedCron(cronSettings)
}
}
I am trying to merge two yamls in jenkins file (.Jenkinsfile)
def runConf = """
fail_fast: false
tests:
- ABC:
"""
print(runConf)
def defaultRunConfig = """
test:
- ABC.json
- DEF.json
Seconds: 60
Type: dynamic
"""
def runConfigObj
runConfigObj = readYaml([text:defaultRunConfig])
String time = defaultRunConfig.Seconds.toString()
echo ("Duration for run: " +time)
def runConfigBase
runConfigBase = readYaml([text:runConf])
Map<Object, Object> runConfiguration = [:]
runConfiguration.putAll(runConfigBase)
print(runConfiguration)
for (tests in runConfigObj.test) {
print(runConfigObj.test)
runConfiguration.put(runConfigObj.test)
}
runConfiguration['Seconds'] = runConfigObj.Seconds.toString()
runConfiguration['Type'] = runConfigObj.Type
Expectation is to get something like:
fail_fast: false
tests:
- ABC:
test:
- ABC.json
- DEF.json
Seconds: 60
Type: dynamic
But I am getting below Error:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.LinkedHashMap.put() is applicable for argument types: (java.util.ArrayList) values:
Tried looking into options like MAP in groovy but not able to resolve the issue
How to avoid such an error? I am new to groovy, any help is much appreciated
So you want to add an array of "tests" as values to the key test into a map object of runConfiguration, then it should be something like this:
runConfiguration['test']=[]
for (test in runConfigObj) {
runConfiguration['test'].add(test)
}
I have a pipeline job which run some sequence of action (Eg; Build >> Run >> Report). I have put this sequence in a for loop as I can get a parameter which has list of value for which I should repeat the same sequence. Please find the sample code I have written.
param_val = params.param_1
param_list = param_val.split()
for (int i = 0; i < size(param_list); ++i){
item_value = param_list[i].trim()
builds[i] ={
stage('Build') {
build 'Build', parameters: [string(name: 'item', value: item_value)]
}
stage('Run') {
build 'Run', parameters: [string(name: 'item', value: item_value)]
}
stage('Reporting') {
build 'Reporting', parameters: [string(name: 'item', value: item_value)]
}
}parallel builds
}
I can get even more than 100 values for the iteration. So it is difficult to track it in the pipeline stage view. it just grows to right side.
Do we have any other plugin which can be used for the status view ? Some tree like view would be good.
I’m trying to push stage data from Jenkins pipeline to influx db and I get issue as below
Issue: In jenkin builds console output, after each stage, I see : java.io.NotSerializableException: sun.net.www.protocol.http.HttpURLConnection
Jenkins pipeline 2.150.2
InfluxDB 1.6.2
Any suggestions would be helpful. I'm new to this topic.
Note: I have commented #NonCPS annotation. If I uncomment then it sends only first stage data and exits and fails to iterate for loop which has 20 stages data.
//Maps for Field type columns
myDataField1 = [:]
myDataField2 = [:]
myDataField3 = [:]
//Maps for Custom Field measurements
myCustomDataFields1 = [:]
myCustomDataFields2 = [:]
myCustomDataFields3 = [:]
//Maps for Tag type columns
myDataTag1 = [:]
myDataTag2 = [:]
myDataTag3 = [:]
//Maps for Custom Tag measurements
myCustomDataTags1 = [:]
myCustomDataTags2 = [:]
myCustomDataTags3 = [:]
//#NonCPS
def pushStageData() {
def url_string = "${JENKINS_URL}job/ENO_ENG_TP/job/R421/13/wfapi/describe"
def get = new URL(url_string).openConnection();
get.addRequestProperty ("User-Agent","Mozilla/4.0");
get.addRequestProperty("Authorization", "Basic dZXZvceDIwMTk=");
//fetching the contents of the endpoint URL
def jsonText = get.getInputStream().getText();
//converting the text into JSON object using
JsonSlurperClassic
def jsonObject = new JsonSlurperClassic().parseText(jsonText)
// Extracting the details of all the stages present in that particular build number
for (int i=0; i<jsonObject.stages.size()-1; i++){ //size-1 to ignore the post stage
//populating the field type columns of InfluxDB measurements and pushing them to the map called myDataField1
def size = jsonObject.stages.size()-1
myDataField1['result'] = jsonObject.stages[i].status
myDataField1['duration'] =
jsonObject.stages[i].durationMillis
myDataField1['stage_name'] = jsonObject.stages[i].name
//populating the tag type columns of InfluxDB
measurements and pushing them to the map called
myDataTag1
myDataTag1['result_tag'] = jsonObject.stages[i].status
myDataTag1['stage_name_tag'] = jsonObject.stages[i].name
//assigning field type columns to the measurement called CustomData
myCustomDataFields1['CustomData'] = myDataField1
//assigning tag type columns to the measurement called CustomData
myCustomDataTags1['CustomData'] = myDataTag1
//Push the data into influx instance
try
{ step([$class: 'InfluxDbPublisher', target: 'jenkins_data', customPrefix: null, customDataMapTags: myCustomDataTags1]) }
catch (err)
{ println ("pushStagData exception: " + err) }
}
}
Expected: I want to push each stages of jenkins pipeline data to influx db.
Try to use jenkins' standard methods instead of creating objects manually. You can use httpRequest instead of URL. This should fix exception you are getting. You can also use readJson instead of JsonSlurperClassic (latter is optional since classic slurper is actually serializable).
you just need to explicitly set get to null to make sure there's none non serializable object being instantiated.
def jsonText = get.getInputStream().getText();
get = null;