How to call Jenkins parameter inside a groovy script - jenkins

Can any one tell me how to call jenkin parameter value into the groovy script?
Im creating a jenkins job that give permission to a another job for a perticular User.
below pic shows the parameter. i want to call that parameter value into the groovy script
please find the script below:
import hudson.model.AbstractProject
import hudson.model.Item
import hudson.security.AuthorizationMatrixProperty
import hudson.security.Permission
AbstractProject proj = hudson.model.Hudson.instance.getItem("testjob")
AuthorizationMatrixProperty authProperty = proj.getProperty(AuthorizationMatrixProperty.class)
Set<String> users = new HashSet<>();
users.add('userid'); // XXX
Map<Permission,Set<String>> newPermissions = new HashMap<Permission, Set<String>>()
newPermissions.put(Item.READ, users)
proj.addProperty(new AuthorizationMatrixProperty(newPermissions))
proj.save()
That parameter value should have to come here userid in the groovy script
can any one tell me how to call jenkin parameter value into the groovy script
Thanks in advance

I think the asnwer your`e looking for is this:
string(name: 'UserID', defaultValue: '',description: 'Enter ID here')

Related

How to add string parameter to a freestyle jenkins job via groovy?

I am new to Groovy and trying to add a string parameter to a Jenkins job via Groovy (not using plugins)
I found similar set of examples for Workflow job and not for FreeStyleProject
https://www.programcreek.com/java-api-examples/index.php?api=hudson.model.FreeStyleProject
If anyone could help me it would be great
After searching for days, the following solution worked
ParameterDefinition paramDef = new StringParameterDefinition("CUSTOM_BUILD_PARAM", "Test", "");
ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef);
job.addProperty(paramsDef);
where 'job' is of type 'FreeStyleProject'
You can use String Parameter Definition
It accepts 3 parameters
new StringParameterDefinition(parameterName, defaultValue, description)
Also, be sure to import it!
import hudson.model.*

How to trigger a different jobs in a master job

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")]))
}

trigger parameterized build with groovy variable

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.

Way to change Jenkins' project variable value with script

Is there a way to change project variable values in Jenkins automatically when build is done?
In my case i got a variable VERSION, default value is 1. And i need to increment this default value every build done. Assuming build stars by cron in this case. Any plugins can help me?
Now i have something like this: My build steps.
It is a single working way to get project variable in my groovy script that i found. Now how can i set new value for variable?
I read some similar question on SO, but didn't found a working way for me.
P.S. I can't use $BUILD_NUMBER var, because i need a possibility to set VERSION manually when i start build.
First, of all, install the plugins Global Variable String Parameter Plugin and Groovy Postbuild Plugin. Under Manage Jenkins -> Configure System you should now have a part, called Global Properties. There you add a new variable. In my tests, I called it SOME_VER.
At your job, you now add a Groovy postbuild part with this code adjusted to your variable:
import jenkins.*;
import jenkins.model.*;
import hudson.*;
import hudson.model.*;
import java.lang.*;
instance = Jenkins.getInstance();
globalNodeProperties = instance.getGlobalNodeProperties();
envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class);
envVars = null
if (envVarsNodePropertyList != null && envVarsNodePropertyList.size() > 0)
{
envVars = envVarsNodePropertyList.get(0).getEnvVars()
String value = envVars.get("SOME_VER", "0")
int NEW_VER = Integer.parseInt(value)
NEW_VER = NEW_VER + 1
envVars.override("SOME_VER", NEW_VER.toString());
}
instance.save()
Parts of this code are taken from here. This code does nothing else than retrieving the value of the global variable, change it and save the new value of the variable.

Need help to read a json file using groovy and Jenkins

I am facing some issues reading a JSON file.
I am using Jenkins Active Choice Parameter to read value from a JSON file via groovy script. This is how my JSON file look.
{
"smoke": "Test1.js",
"default": "Test2.js"
}
I want my groovy script to print out smoke and default. Below is what my groovy code look like.
import groovy.json.JsonSlurper
def inputFile = new File(".\TestSuitesJ.json")
def InputJSON = new JsonSlurper().parseText(inputFile)
InputJson.each
{
return[
key
]
}
Above code is not working for me. Can someone please suggest a better groovy way?
Anyone in similar situation as me trying to import a JSON file at runtime. I used Active Choice parameter to solve my problem. There is an option to write groovy script in Active Choice Parameter plugin of Jenkins. There i have written below code to import a JSON file to achieve desired results.
import groovy.json.JsonSlurper
def inputFile = new File('.//TestSuitesJ.json')
def inputJSON = new JsonSlurper().parse(inputFile)
def keys = inputJSON.keySet() as List
Thanks #sensei to help me learn groovy.
You really should read the groovy dev kit page, and this in particular.
Because in your case parseText() returns a LazyMap instance, the it variable you're getting in your each closure represents a Map.Entry instance. So you could println it.key to get what you want.
A more groovy way would be:
inputJson.each { k, v ->
println k
}
In which case groovy passes your closure the key (k) and the value (v) for every element in the map.

Resources