I have this pipeline job that needs to call a validation job like this:
isHardReleaseAllowed= true
def versionOk = build(job: "/validateMVNVersion", parameters: [[$class: 'StringParameterValue', name: 'version', value: params.version],
[$class: 'BooleanParameterValue', name: 'isHardReleaseAllowed', value: isHardReleaseAllowed]], propagate: true)
The validate job is defined as follows :
string(name: 'version', description: 'The new version to set')
booleanParam(name: 'isReleaseTagAllowed',defaultValue: false , description: 'is hard release tag allowed?')
These are my values before calling my job (from the output console) :
echo ➡ validating version 1.12.14 tag on branch ➡release/testRelease with isHardReleaseAllowed= true
But when I echo these in my validateMVNVersion job ,
echo "isReleaseTagAllowed class : \u27A1" + isReleaseTagAllowed.getClass().toString() + " value :" + isReleaseTagAllowed
echo "env.isReleaseTagAllowed \u27A1" + env.isReleaseTagAllowed.getClass().toString() + " value :" + env.isReleaseTagAllowed
echo "params.isReleaseTagAllowed \u27A1" + params.isReleaseTagAllowed.getClass().toString() + " value :" + params.isReleaseTagAllowed
boolean isReleaseBranchAllowedBoolean = params.isReleaseTagAllowed == "true"
echo "Boolean asboolean value is " + isReleaseBranchAllowedBoolean
I get these values :
isReleaseTagAllowed class : ➡class java.lang.String value :false
[Pipeline] echo
env.isReleaseTagAllowed ➡class java.lang.String value :false
[Pipeline] echo
params.isReleaseTagAllowed ➡class java.lang.Boolean value :false
[Pipeline] echo
Boolean asboolean value is false
All of them are false... What am I not getting?
A good way of getting the value is by setting the right variable name ;)
Related
Am looking for any Plugin from which I can pull the data which contains total number of jenkins jobs, total number of build failure happened periodically.
Edit 1: Getting below error
referring this method List Jenkins job build detials for last one year along with the user who triggered the build
error:
Building on the built-in node in workspace /data-1/ondotapps/jenkins/workspace/Finding overall build details
Job Name: ( # builds: last 365 days / overall ) Last Status
Number | Trigger | Status | Date | Duration
ERROR: Build step failed with exception
groovy.lang.MissingPropertyException: No such property: Jenkins for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:66)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:310)
at Script1.run(Script1.groovy:7)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:574)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:612)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:583)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:440)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:377)
at hudson.plugins.groovy.SystemGroovy.run(SystemGroovy.java:95)
at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:59)
at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:816)
at hudson.model.Build$BuildExecution.build(Build.java:199)
at hudson.model.Build$BuildExecution.doRun(Build.java:164)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:524)
at hudson.model.Run.execute(Run.java:1897)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:44)
at hudson.model.ResourceController.execute(ResourceController.java:101)
at hudson.model.Executor.run(Executor.java:442)
Build step 'Execute system Groovy script' marked build as failure
Started calculate disk usage of build
Finished Calculation of disk usage of build in 0 seconds
Started calculate disk usage of workspace
Finished Calculation of disk usage of workspace in 0 seconds
Finished: FAILURE
edit 2:
Am running the script as "Execute system Groovy Step" in build section of freestyle job.
Below image for your reference.
enter image description here
and at the same time I have tried running the same script at manage jenkins-> script console part as well.
Still getting below error.
error:
Job Name: ( # builds: last 365 days / overall ) Last Status
Number | Trigger | Status | Date | Duration
groovy.lang.MissingPropertyException: No such property: instance for class: Script1
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:66)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:51)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:310)
at Script1$_run_closure1.doCall(Script1.groovy:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:98)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:264)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1034)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:41)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
Please let me know if am missing something here.
I made a code to obtain a "Resume" of all Jobs with FAILURES, SUCCESSES AND UNSTABLES, each Job and Total of all Jobs. Also you can insert number of days, by default will get all Jobs in 1 day and check numbers of FAILURES, SUCCESSES AND UNSTABLES.
This is a pipeline.
properties([disableConcurrentBuilds(),buildDiscarder(logRotator(artifactDaysToKeepStr: '1', artifactNumToKeepStr: '', daysToKeepStr: '1', numToKeepStr: '')),pipelineTriggers([cron('H 1 * * *')]),parameters([string(defaultValue: 'NO', name: 'SHOW_LIST'),string(defaultValue: '1', name: 'DAYS'),string(defaultValue: '.*', name: 'FILTER',description:'''Use ".*" for all jobs
''')])])
#NonCPS
def Funcion(){
int value = env.DAYS as Integer
def jobNamePattern =env.FILTER
def daysBack = value
def timeToDays = 24*60*60*1000
def myList= ""
def C_Fail_T=0
def C_Unst_T=0
def C_Succ_T=0
// Bash colors:
def RED='\033[1;31m'
def BLUE='\033[1;34m'
def GREEN='\033[1;32m'
def YELLOW='\033[1;33m'
def ORANGE='\033[0;33m'
def MAGENTA='\033[1;35m'
def PURPLE='\033[1;35m'
def CIAN='\033[1;36m'
def NC='\033[0m'
def TOTAL= Jenkins.instance.allItems.findAll() {
it instanceof Job && it.fullName.matches(jobNamePattern)
}.each {job ->
def builds = job.getBuilds().byTimestamp(System.currentTimeMillis() - daysBack*timeToDays, System.currentTimeMillis())
// individual build details
def C_Fail=0
def C_Unst=0
def C_Succ=0
//if(job.fullName.equals(excluid.findAll { it > job.fullName.toString() }) )
//{
//}
builds.each {def build ->
if(build.result == hudson.model.Result.FAILURE) { C_Fail=C_Fail+1}
if(build.result == hudson.model.Result.UNSTABLE){ C_Unst=C_Unst+1}
if(build.result == hudson.model.Result.SUCCESS) { C_Succ=C_Succ+1}
}
C_Fail_T = C_Fail_T + C_Fail
C_Unst_T = C_Unst_T + C_Unst
C_Succ_T = C_Succ_T + C_Succ
myList= myList+ "\n" + (job.fullName + ' ( ' + builds.size() + ' / ' + job.builds.size() + ' ) ' + "in " + daysBack + " day/s " + "LAST STATUS: "+job.getLastBuild()?.result +" | "+RED+ "FAILURE: "+C_Fail +ORANGE+ " UNSTABLE: " + C_Unst +GREEN+ " SUCCESS: " + C_Succ+NC)
// individual build details
//builds.each { build ->
// println ' ' + build.number + ' | ' + build.getCauses()[0].getShortDescription() + ' | ' + build.result + ' | ' + build.getTimestampString2() + ' | ' + build.getDurationString()
//}
}
job=null
build=null
builds=null
jobNamePattern=null
if(env.SHOW_LIST=="YES"){
println(myList)
}
println("RESUME Jobs in "+DAYS+" day/s "+GREEN+": SUCCESS " +C_Succ_T +NC+RED+ " FAILED "+C_Fail_T+NC+ORANGE+" UNSTABLE " +C_Unst_T +NC)
if(C_Succ_T==0 && C_Unst_T==0 && C_Fail_T==0)
{
println("FILTER input wrong")
currentBuild.result('FAILURE')
}
}
timestamps {
withCredentials([usernamePassword(credentialsId: '501b9ef0-5c12-4b19-9cd1-1fcd87e37aec', passwordVariable: 'OS_PASSWORD', usernameVariable: 'OS_USERNAME')]) {
ansiColor('xterm') {
String repoUrl = "YOUR_REPO_IF_NEED"
node{
echo 'Clearing workspace before cloning: '
cleanWs()
// Clones the repository from the current branch name
git credentialsId: 'credentialsId', url: repoUrl
Funcion()
}
} //USER
} //XTERM
} //TIMESTAMP
I use XTERM to add color to your Terminal, if you dont use it, please delete that "{}" brackets and delete "// Bash colors:" part.
Hope you understand me.
Franco
EDIT: You will have to give some permission in "<URL_OF_YOUR_JENKINS>/jenkins/scriptApproval/"
I have the following input in one of my Jenkins Pipeline Scripts:
def IMAGE_TAG = input message: 'Please select a Version', ok: 'Next',
parameters: [choice(name: 'IMAGE_TAG', choices: imageTags, description: 'Available Versions')]
imageTags is a List of map e.g. :
imageTags : [
[targetSuffix: "", sourceSuffix: "v2.17.1"],
]
When I run the script, I can select only [targetSuffix: "", sourceSuffix: "v2.17.1"] from the dropdown choice as expected.
In my script I can also see the value that gets selected:
echo "Selected Version = ${env.SELECTED_IMAGE_TAG}"
[Pipeline] echo Selected Version = {targetSuffix=, sourceSuffix=v2.17.1}
Now I wanted to find out which item from the original imageTags List got selected, but my script does not work as expected:
def selectedImageTag = imageTags.find { it.targetSuffix == "${env.SELECTED_IMAGE_TAG.targetSuffix}" }
I end up with the following exception:
groovy.lang.MissingPropertyException: No such property: targetSuffix for class: java.lang.String
My question is: How do I get the selected item of my choice out of the original List of maps?
The input step returns a string, so you can't write env.SELECTED_IMAGE_TAG.targetSuffix. You have to extract the substring, e. g. using a regular expression like this:
def match = ( env.SELECTED_IMAGE_TAG =~ /\{targetSuffix=(.*?), sourceSuffix=(.*?)\}/ )
if( match ) {
def selectedTargetSuffix = match[0][1]
def selectedImageTag = imageTags.find { it.targetSuffix == selectedTargetSuffix }
}
I used in my pipeline a input steps as you can see below :
input(
message : "some message",
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: string ,
description: 'description',
name:'input'
]
]
)
I wanted to use the name input that I configure to get the value put in the input like this ${input}, but it didn't work. I also tried to put it in a var like this :
def reg = input : messages : "", paramaters: [...]
But It doesn't work either, so I don't understand how I can get the param that the user chose and didn't find how to do in the do.
Regards,
When using ChoiceParameterDefinition remember to define choices as string delimited with \n. You can assign value returned by input(...) step to a variable and use it later on. Take a look at following example:
node {
stage('Test') {
def reg = input(
message: 'What is the reg value?',
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: 'Choice 1\nChoice 2\nChoice 3',
name: 'input',
description: 'A select box option']
])
echo "Reg is ${reg}"
}
}
In this example I define a single select with 3 options. When I run this pipeline, I get this popup to select one of three options:
I pick the first one and pipeline finishes with following console output:
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] input
Input requested
Approved by admin
[Pipeline] echo
Reg is Choice 1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Try use this code:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description', name:'input'],
])
VARAIBLE = userInput
It's work For me.
If you need add more ChoiceParameterDefinition code should look like that:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description1', name:'input1'],
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description2', name:'input2'],
])
VARAIBLE1 = userInput['input1']
VARAIBLE2 = userInput['input2']
currently I wish to added a multliline text parmeter to a groovy pipeline. If the text parameter is not left column alighed (no space before paramter), then whitespace is injected into the text parameter list.
Any ideas on how to resolve this?
Here is the code
#!/usr/bin/env groovy
node {
def startTime = new Date()
println "Build start time : " + startTime
// Load system parameters
def projectProperties = [
[$class: 'EnvInjectJobProperty', info: [loadFilesFromMaster: false, secureGroovyScript: [classpath: [], sandbox: false, script: '']], keepBuildVariables: true, keepJenkinsSystemVariables: true, on: true]
]
// Set project parameters
projectProperties.add(parameters([
string(name: 'infraRepo', description: 'Repo Name', defaultValue: 'my-infrastructure' ),
string(name: 'infraBranch', description: 'Repo Branch', defaultValue: 'develop' ),
string(name: 'projectName', description: 'Project name', defaultValue: 'think-more' ),
// Text field not left side aligned now whitespace will be injected
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and version number',
defaultValue:'''address=3.0.1
address-details=3.0.1
auth=3.2.1'''),
choice(name: 'clusterName', description: 'Ecs cluster name', choices: '---Select---\nblue-ci\ngreen-ci', defaultValue: '---Select---'),
]))
properties(projectProperties)
// Print system variables
sh 'env | sort'
}
And here is an image of how the Jenkins Job UI looks after this pipeline is executed. Note the whitespace in the ecrRepoAndVersion field.
Thank you - that worked perfectly.
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and
version number',defaultValue:"""address=3.0.7-RC\n
address-details=3.0.3-RC\nauth=3.2.3-RC""")
Setting aside the need for this logic, I would add a bit more readability and ease of maintenance by joining a list of items, instead of verbatim specification:
def ecrRepoAndVersionItemsDefault = [
"address=3.0.7-RC",
"address-details=3.0.3-RC",
"auth=3.2.3-RC",
]
...
// then construct an ArrayList
def jobParams = []
jobParams << ...
...
jobParams << text(
name: 'ecrRepoAndVersion',
description: 'ECR Docker name and version number',
defaultValue: ecrRepoAndVersionItemsDefault.join('\n')
)
// then add the properties
...
projectProperties.add(parameters(jobParams))
...
properties(projectProperties)
...
// etc.
I have a job trigger (upstream job) parametrized with uno-choice dynamic choice parameter, to trigger a multiple jobs (downstream jobs).
trigger job parameters:
and i'm using this script that trigger selected jobs using the post-build actions -> groovy post build:
// param list of jobs to execute coming from upastream Job
def upstreamParam = "JOB_LIST_TRIGGER"
def upstreamParamFlag = "NEXT_RELEASE_TYPE"
def resolver = manager.build.buildVariableResolver
def JOBS_TO_EXECUTE = resolver.resolve(upstreamParam)
def FLAG = resolver.resolve(upstreamParamFlag )
def viewName = "test"
def jobsName = []
//only the NEXT RELEASE TYPE
def params = new hudson.model.StringParameterValue('NEXT_RELEASE_TYPE_BIS', FLAG)
// if no job selected in the parameter, will trigger all jobs in the view "test", otherwise will execute only selected jobs
if (JOBS_TO_EXECUTE == null || JOBS_TO_EXECUTE == ''){
// retrieve jobs names from jenkins view
hudson.model.Hudson.instance.getView(viewName).items.each() {
jobsName.push(it.getDisplayName())
}
// launch plugins jobs
jobsName.each(){
job = manager.hudson.getItem(it)
cause = new hudson.model.Cause.UpstreamCause(manager.build)
def paramsAction = new hudson.model.ParametersAction(params)
causeAction = new hudson.model.CauseAction(cause)
manager.hudson.queue.schedule(job, 0, causeAction, paramsAction)
}
}else{
// create a list of selected jobs in the JOB_LIST_TRIGGER param
hudson.model.Hudson.instance.getView(viewName).items.each() {
if (JOBS_TO_EXECUTE.contains(it.getDisplayName())){
jobsName.push(it.getDisplayName())
}
}
// launch only job selected in the JOB_LIST_TRIGGER param
jobsName.each(){
job = manager.hudson.getItem(it)
cause = new hudson.model.Cause.UpstreamCause(manager.build)
def paramsAction = new hudson.model.ParametersAction(params)
causeAction = new hudson.model.CauseAction(cause)
manager.hudson.queue.schedule(job, 0, causeAction, paramsAction)
}
}
in this code i only trigger NEXT_RELEASE_PARAMETER to the downstream jobs.
job1..job4 with below details to display the current job details.
echo "------------------------------------------------"
echo "------------------------------------------------"
# the current param
echo $RELEASE_VERSION
echo "------------------------------------------------"
echo "------------------------------------------------"
# the current param
echo $NEXT_RELEASE_TYPE
echo "------------------------------------------------"
echo "------------------------------------------------"
# the upstream param
echo $NEXT_RELEASE_TYPE_BIS
echo "------------------------------------------------"
echo "------------------------------------------------"
# the current param
echo $NEXT_RELEASE
echo "------------------------------------------------"
echo "------------------------------------------------"
the output is:
+ echo ------------------------------------------------
------------------------------------------------
+ echo
+ echo ------------------------------------------------
------------------------------------------------
+ echo ------------------------------------------------
------------------------------------------------
+ echo
+ echo ------------------------------------------------
------------------------------------------------
+ echo ------------------------------------------------
------------------------------------------------
+ echo Major
Major
+ echo ------------------------------------------------
------------------------------------------------
+ echo ------------------------------------------------
------------------------------------------------
+ echo
+ echo ------------------------------------------------
------------------------------------------------
+ echo ------------------------------------------------
------------------------------------------------
the result prints only the upstream param but not the current parameters, so is there any way to get downstream (job1..job4) current parameters after it was triggred by job-trigger?