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

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.*

Related

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

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.

gradle test fail when using slackNotifier in Jenkins Job DSL definition

Update:
From the bottom of the Automatically Generated DSL wiki entry ... The generated DSL is only supported when running in Jenkins,....
Since slackNotifier is generated DSL, it doesn't appear that there is a way to test this in our particular infrastructure. We're going to write a function which generates the config using the configure block.
I have a seed job definition which is failing gradle test even though it seems to work fine when we use it in Jenkins.
Job Definition Excerpt
//package master
// GitURL
def gitUrl = 'https://github.com/team/myapp'
def slackRoom = null
job('seed-dsl') {
description('This seed is updated from the seed-dsl-updater job')
properties {
//Set github project URL
githubProjectUrl(gitUrl)
}
...
// publishers is another name for post build steps
publishers {
mailer('', false, true)
slackNotifier {
room(slackRoom)
notifyAborted(true)
notifyFailure(true)
notifyNotBuilt(true)
notifyUnstable(true)
notifyBackToNormal(true)
notifySuccess(false)
notifyRepeatedFailure(false)
startNotification(false)
includeTestSummary(false)
includeCustomMessage(false)
customMessage(null)
buildServerUrl(null)
sendAs(null)
commitInfoChoice('NONE')
teamDomain(null)
authToken(null)
}
}
}
The gradle test command works fine when I comment out the with the slackNotifier declaration, but fail with the following error when it's enabled:
Test output excerpt
Caused by:
javaposse.jobdsl.dsl.DslScriptException: (script, line 79) No signature of method: javaposse.jobdsl.dsl.helpers.publisher.PublisherContext.slackNotifier() is applicable for argument types: (script$_run_closure1$_closure9$_closure14) values: [script$_run_closure1$_closure9$_closure14#d2392a1]
Possible solutions: stashNotifier(), stashNotifier(groovy.lang.Closure)
at javaposse.jobdsl.dsl.DslScriptLoader.runScriptEngine(DslScriptLoader.groovy:135)
at javaposse.jobdsl.dsl.DslScriptLoader.runScriptsWithClassLoader_closure1(DslScriptLoader.groovy:78)
According to the migration doc, slackNotifer has been supported since 1.47. In my gradle.build, I'm using 1.48. I see the same errors with plugin version 1.50
gradle.build excerpt
ext {
jobDslVersion = '1.48'
...
}
...
// Job DSL plugin including plugin dependencies
testCompile "org.jenkins-ci.plugins:job-dsl:${jobDslVersion}"
testCompile "org.jenkins-ci.plugins:job-dsl:${jobDslVersion}#jar"
...
The gradle.build also includes the following, as suggested by the [testing docs] *(https://github.com/jenkinsci/job-dsl-plugin/wiki/Testing-DSL-Scripts).
testPlugins 'org.jenkins-ci.plugins:slack:2.0.1'
What do I need to do to be able to successfully test my job definitions. Is this a bug, or have I missed something else?
removed incorrect reply
EDIT
I see I missed the point.
The new approach is to reuse the #DataBoundConstructor exposed by plugins, so nothing needs to be written to support a new plugin assuming it has a DataBoundConstructor
Your SlackNotifier has this - note the DSL converts the lowercase first letter for you
#DataBoundConstructor
public SlackNotifier(
final String teamDomain,
final String authToken,
final String room,
final String buildServerUrl,
final String sendAs,
final boolean startNotification,
final boolean notifyAborted,
final boolean notifyFailure,
final boolean notifyNotBuilt,
final boolean notifySuccess,
final boolean notifyUnstable,
final boolean notifyBackToNormal,
final boolean notifyRepeatedFailure,
final boolean includeTestSummary,
CommitInfoChoice commitInfoChoice,
boolean includeCustomMessage,
String customMessage) {
...
}
Unfortunately there is an embedded type in the parameter list CommitInfoChoice and this does not have a DataBoundConstructor and its an enum too.
public enum CommitInfoChoice {
NONE("nothing about commits", false, false),
AUTHORS("commit list with authors only", true, false),
AUTHORS_AND_TITLES("commit list with authors and titles", true, true);
...
}
I'll go out on a limb and say that it won't work out the box until the nested enum implements a databound constructor and also has a descriptor, sorry.
I don't have the plugin but you can look at the XML for a real created job with the plugin and see what goes into this section. I suspect it is a nested structure
You can try the job dsl google group - link to a post about the generic approach
We ran into this as well. The solution for us was to add the slack plugin version we were using on jenkins to our list of plugins in gradle.
To be more specific, in our build.gradle file under dependencies, we added the following code to get our plugins included and hence allow the auto-generated DSL to work.
You can see this described here and an example of a different plugin next to testPlugins:
https://github.com/jenkinsci/job-dsl-plugin/wiki/Testing-DSL-Scripts
Like the following:
dependencies {
...
// plugins to install in test instance
testPlugins 'org.jenkins-ci.plugins:ghprb:1.31.4'
testPlugins 'com.coravy.hudson.plugins.github:github:1.19.0'
}

How to call Jenkins parameter inside a groovy script

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')

Resources