I am trying to create a dynamic choice parameter that will be populated by the resulting values of a groovy script.
The following code works and lists the contents of a dir:
new File("/tmp/testing/source/").eachFile() { file->
println file.getName()
}
I created a new jenkins project, and entered the menu 'Configure' where I selected This project is parameterized
When I save and try to build with parameters nothing has been parsed from the groovy script
Solved with the following code:
list = []
def process = "ls /tmp/testing/source".execute()
process.text.eachLine {list.add it}
return list
Related
I have a job which contains a field of type string parameter (called JOB_NAME), in this string parameter, I will just fill it with another job name.
in the same job, I created "trigger/call builds on another project", in the latest, I will just provide the $JOB_NAME but it is not working.
My second question is how to fill $JOB_NAME field with some existing job using regular expresion or something else.
Can someone provide me clear steps, I am not that expert in Jenkins.
Thanks a lot
You can use Groovy Postbuild Plugin to achieve this.
Once you install the plugin, go to Post-build Actions and choose Groovy Postbuild option and add the following script to it.
Then, whenever you run your job it will ask for JOB_NAME as you have defined it as a parameter in your job and whatever project name you will enter, it will trigger that job in the downstream.
import hudson.model.*
import jenkins.model.*
def build = Thread.currentThread().executable
def jobPattern = manager.build.buildVariables.get("JOB_NAME")
def matchedJobs = Jenkins.instance.items.findAll { job ->
job.name =~ /$jobPattern/
}
matchedJobs.each { job ->
println "Triggering ${job.name} in the down stream...."
job.scheduleBuild(1, new Cause.UpstreamCause(build), new ParametersAction([ new StringParameterValue("PROPERTY1", "PROPERTY1VALUE"),new StringParameterValue("PROPERTY2", "PROPERTY2VALUE")]))
}
I have a pipeline job running in Jenkins and I want to know the name of the node it's running on. Is there a way to get the node name from within the job's Groovy script?
I have tried the below code:
print currentBuild.getBuiltOn().getNodeName()
the error is:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified method org.jenkinsci.plugins.workflow.job.WorkflowRun getBuiltOn
I also tried this:
def build = currentBuild.build()
print build.getExecutor().getOwner().getNode().getNodeName()
but the result is ''.
There is an environment variable 'NODE_NAME' which has this.
You can access it like this:
echo "NODE_NAME = ${env.NODE_NAME}"
When you are editing a pipeline job, you can find all the available environment variables by going to the "pipeline syntax" help link (left of page) then look for the "Global Variables" section and click through to the "Global Variables Reference". There is a section "env" that lists the environment variables available.
It is not documented, but indeed Node and Executor objects can be obtained from CpsThread class of the pipeline. Of course, they are defined only inside node { } block:
import org.jenkinsci.plugins.workflow.cps.CpsThread;
#NonCPS
obtainContextVariables() {
return CpsThread.current().getContextVariables().values;
}
node('myNode') {
print('Node: ' + obtainContextVariables().findAll(){ x -> x instanceof Computer }[0].getNode())
print('Executor: ' + obtainContextVariables().findAll(){ x -> x instanceof Executor }[0])
}
I have an Jenkins Freestyle job with an system groovy script in the Build area. After executing the script I want to trigger a pipeline job. The pipeline job needs a variable who gets defined inside my groovy scipt.
if(condition1){
var = 'String1'
}else{
var = 'String2'
}
But I need to get acces to my variable var at the "post-build-action" step at the "Trigger parameterized build on other projects" option to trigger my pipeline with var as parameter. Is this possible?
Yes, it is possible. You can simply write your variables as key-value pairs in a property file and load it in your post-build-action by specifying Parameters from properties file.
You can save your property file like this
def fw = new OutputStreamWriter(new FileOutputStream("params.properties",true), 'UTF-8')
def props = new Properties()
props.setProperty('TESTPARAM', var)
props.store(fileWriter, null)
fw.close()
I solved my problem the following way:
Before building I define a parameter to use the parameterized trigger plugin. Inside my system groovy script I override it with
def newMailParameter = new StringParameterValue('MAIL_PARAM', mailsFromWS)
build.replaceAction(new ParametersAction(newMailParameter))
Now I can trigger the next job and use my parameter MAIL_PARAM inside of it.
I have a parameterized build like below:
then i've create a groovy script to create a variable URL_TOMCAT where its value depends on the TARGET_TOMCAT parameter:
Even after this update i got the same error
import hudson.model.*
def target = build.buildVariableResolver.resolve("TARGET_TOMCAT")
def URL_TOMCAT = ""
switch(target ) {
case "tomcat1": URL_TOMCAT= "http://localhost:8080/manager/text"
break
case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
break
}
Then i want to get The URL_TOMCAT value and adjust the maven build step as shown:
But i got this error :
Has any on an idea how to fix this error?
In your groovy script you need to make an API call to get the value of the parameter from Jenkins into your workspace.
Import hudson.model
def targetTomcat = build.buildVariableResolver.resolve("TARGET_TOMCAT")
def URL_TOMCAT = ""
switch(targetTomcat) {
case "tomcat1": URL_TOMCAT = "http://localhost:8080/manager/text"
break
case "tomcat2": URL_TOMCAT = "http://localhost:8089/manager/text"
break
}
I want to point out that the URL_TOMCAT variable won't be available to any other buildsteps, it's scoped to just the groovy build step. If you want to expose your URL_TOMCAT variable to the rest of the build you'll need to expose it to the build environment somehow. I normally do this by writing the value to a file as a key value pair and using the EnvInject Plugin
You can write it to a file in groovy like so:
def workspace = build.buildVariableResolver.resolve("WORKSPACE")
new File("${workspace}\\Environment.Variables").write("URL_TOMCAT=${URL_TOMCAT}")
If you don't want to write it to the jobs workspace you can skip grabbing that value and just code a specific path.
After your groovy build step add an Envinject build step and enter the path to the file containing the key value pair in the Properties File Path field. You should be able to reference URL_TOMCAT like any other environment variable in the rest of the build. Continuing with the about path I would use ${WORKSPACE}\Environment.Variables as the path.
This is my requirement to have parameters in Jenkins:
1. User selects 3 Values from Dropdown: DEV, QA, PROD
2. Upon selection I need to return single value as parameter as like this:
If DEV selected, return "Development http://dev.com 1"
If QA selected, return "QA http://qa.com 2"
If PROD selected, return "Production http://prod.com 3"
3. Once the value is returned in a variable, I will use that variable value in next step of 'Windows batch command'.
Where and How can define Key/Values. I tried to use Extended Choice Parameter plugin, but not sure how to do this.
I have managed to get the keys/values with a dropdown select parameter working with the Active Choices Plugin, it's not as complicated as the other answer here, and it actually buried in the comments on the plugin page itself.
To get a key/value pair select dropdown list parameter in Jenkins (i.e. show a human readable value, but pass a different key to the build. You simply need to use a map rather than a list when writing your groovy script. The map key is what the parameter will be set to if the user selects this option. The map value is what will be actually displayed to the user in the dropdown list.
For example the script: return ['Key1':'Display 1', 'Key2':'Display 2', 'Key3':'Display 3'] will display a dropdown containing: Display1, Display2 and Display3 to the user. However the build parameter will actually be set to Key1, Key2 or Key3 depending on what is selected.
For this specific question, here are the steps.
Ensure you have the Active Choices Plugin installed.
Open the configuration of your Jenkins job, select This project is parameterised.
Click Add Parameter and select Active Choices Parameter.
Name your parameter and click the Groovy Script check box.
In Groovy Script enter content: return ['Development http://dev.com 1':'DEV', 'QA http://qa.com 2':'QA', 'Production http://prod.com 3':'PROD'] For this example the user will see a dropdown with 3 options: DEV, QA, and PROD. The value passed for this parameter will be Development http://dev.com 1 etc. Now having a parameter with space and URLs may cause issue depending on how you use it later on in the build, but the concept is really what I'm trying to illustrate.
This can be achieved using the Active choice plugin, Find below the link and the image for your reference
Plugin reference: https://wiki.jenkins-ci.org/display/JENKINS/Active+Choices+Plugin
Another method without any plugins
Using shell script this can be achieved
Add a build step as shell script and add the below script that will return your values. Lets say the dropdown paramater name is "env"
if [ $env == "DEV" ]
then
url = "Development http://dev.com 1"
elif [ $env == "QA" ]
then
url = "QA http://qa.com 2"
elif [ $env == "PROD" ]
then
url = "Production http://prod.com 3"
fi
The $url variable will be having the expected value that can be used in your next build steps
Shell Script Reference: http://www.tutorialspoint.com/unix/if-elif-statement.htm
You can do the mapping in a groovy script. If you have a parameter named InputParam, you can map it to a new parameter called OutParam in a System Groovy Script like so:
import hudson.model.*
def parameterMap=[:]
parameterMap.put('DEV','Development http://dev.com 1')
parameterMap.put('QA','QA http://qa.com 2')
parameterMap.put('PROD','Production http://prod.com 3')
def buildMap = build.getBuildVariables()
def inputValue=buildMap['InputParam']
buildMap['OutParam']=parameterMap[inputValue]
setBuildParameters(buildMap)
def setBuildParameters(map) {
def npl = new ArrayList<StringParameterValue>()
for (e in map) {
npl.add(new StringParameterValue(e.key.toString(), e.value.toString()))
}
def newPa = null
def oldPa = build.getAction(ParametersAction.class)
if (oldPa != null) {
build.actions.remove(oldPa)
newPa = oldPa.createUpdated(npl)
} else {
newPa = new ParametersAction(npl)
}
build.actions.add(newPa)
}
Choose Execute system Groovy script as the first build action. You can then access the output param as an environmental variable in the windows shell, eg.
ECHO %OUTPARAM%