use groovy to add an additional parameter to a jenkins job

jenkins dynamic choice parameter groovy script
jenkins parameter based on another parameter
jenkins build parameters list
jenkins extended choice parameter groovy example
jenkins pipeline dynamic parameter
jenkins pipeline powershell parameters
jenkins build with parameters missing
jenkins groovy script parameters

We've got a set of groovy scripts that our users invoke in their jenkinsfile that sets some common job properties. However, we haven't been able to figure out how to preserve their existing parameters when we do this update.

snippet of our groovy code:

def newParamsList = []
def newbool = booleanParam(defaultValue: false, description: "deploy", name: "deploy_flag")
newParamsList.add(newbool)
def newParams = parameters(newParamsList)
properties([ //job property declaration
    jobProperties,
    disableConcurrentBuilds(),
    newParams,
    addSchedule,
  ])

However, this overwrites the parameter definitions, so if the user had specified a different parameter definition in their jenkins file before invoking our groovy, it's been wiped out.

I can get access to the existing parameters using currentBuild.rawBuild.getAction(ParametersAction), but if I understand correctly, I need the ParameterDefinition not the ParameterValue in order to set the property. I tried currentBuild.rawBuild.getAction(ParametersDefinitionProperty.class) thinking I could use that like ParametersAction, but it returns null.

Is it possible to get the parameter definitions inside the groovy being called from a Jenkinsfile? Or is there a different way that would let us add an additional parameter to the job without wiping out the existing ones currently defined in the jenkinsfile?

So the way we do this, is treat it all like a simple list, then join them together. So jenkinsfile's first get a list from the shared library, before adding their own to the list and then they set the params (not the shared library)

Repos jenkinsfiles do this:

#!groovy
@Library('shared') _

// Call shared libaray for common params
def paramList = jobParams.listParams ([
    "var1": "value",
    "var2": "value2"
])
// Define repo specific params
def addtionalParams = [
    booleanParam(defaultValue: false, name: 'SOMETHING', description: 'description?'),
    booleanParam(defaultValue: false, name: 'SOMETHING_ELSE', description: 'description?'),
]
// Set Jenkins job properties, combining both
properties([
    buildDiscarder(logRotator(numToKeepStr: '20')),
    parameters(paramList + addtionalParams)
])

// Do repo stuff

Our shared library looks like this:

List listParams(def body = [:]) {
    //return list of parameters
    config = BuildConfig.resolve(body)

    // Always common params
    def paramsList = [
        choice(name: 'ENV', choices: ['dev', 'tst'].join('\n'), description: 'Environment'),
        string(name: 'ENV_NO', defaultValue: "1", description: 'Environment number'),
    ]

    // Sometimes common params, switch based on jenkinsfile input
    def addtionalParams = []

    switch (config.var1) {
        case 'something':
        case 'something2':
            addtionalParams = [
                choice(name: 'AWS_REGION', choices: ['us-west-2'].join('\n'), description: 'AWS Region to build/deploy'),
            ]
            break
        case 'something3':
            addtionalParams = [
                string(name: 'DEBUG', defaultValue: '*', description: 'Namespaces for debug logging'),
            ]
            break
    }

    return paramsList + addtionalParams
}

How can I trigger another job from a jenkins pipeline (jenkinsfile , There is another plugin called “Extensible Choice Parameter Plug-in”. That is not the one This plugin uses Apache Groovy scripts. Just in case, Groovy Adding an Extended Choice Parameter to a Jenkins Job. Right after  To add a new parameter (REPORT_FILE), based on existing one (JOB_NAME), inject a map with new or modified parameters in the Groovy Script box: // Setting a map for new build parameters def paramsMap = [:] // Set REPORT_FILE based on JOB_NAME def filename = JOB_NAME.replace(' ','_') + ".html" paramsMap.put("REPORT_FILE", filename) // Add or modify other parameters

We did the following groovy code to retrieve the parameters definitions and add new parameters to existing ones (we don't have any knowledge about what the user will put as parameters). If you have something more simple, I take it:

boolean isSupported = true
// nParamsis the List of new parameters to add //
Map initParamsMap = this.initializeParamsMap(nParams)
currentBuild.rawBuild.getParent().getProperties().each { k, v ->
    if (v instanceof hudson.model.ParametersDefinitionProperty) {
        // get each parameter definition
        v.parameterDefinitions.each { ParameterDefinition paramDef ->
            String param_symbol_name = null
            // get the symbol name from the nested DescriptorImpl class
            paramDef.class.getDeclaredClasses().each {
                if(it.name.contains('DescriptorImpl')){
                    param_symbol_name = it.getAnnotation(Symbol).value().first()
                }
            }
            // ...  processing... //
            if( !initParamsMap.containsKey(paramDef.name) ) {
                //Valid parameter types are booleanParam, choice, file, text, password, run, or string.
                if (param_symbol_name == 'choice') {
                    String defaultParamVal = paramDef.defaultParameterValue == null ? null : paramDef.defaultParameterValue.value
                    tempParams.add(
                            "$param_symbol_name"(name: paramDef.name,
                                    defaultValue: defaultParamVal,
                                    description: paramDef.description,
                                    choices: paramDef.choices)
                    )
                } else if (param_symbol_name == 'run') {
                    logError {"buildParametersArray does not support yet already existing RunParameterDefinition " +
                            "in current job parameters list, so the job parameters will not be modified"}
                    isSupported = false
                } else {
                    tempParams.add(
                            "$param_symbol_name"(name: paramDef.name,
                                    defaultValue: paramDef.defaultParameterValue.value,
                                    description: paramDef.description)
                    )
                }
            }
        }
    }
}
if( isSupported) {
    properties([parameters(tempParams)])
}

Jenkins dynamic parameters using Extended Choice Parameter , Using parameters with Jenkins pipeline builds do as you can add custom properties to a Jenkins job which the Groovy scripts can then access. (You can also use env. to get other environment variables, for example env. The Groovy scripting language supports conditional structures, that can be used in Jenkins pipelines. This will allow the user to enter a string which will be exposed to the Jenkins job; Again, drop down the Add Parameter list and select the Choice Parameter.

I think you can also do something like this:

// Get existing ParameterDefinitions
existing = currentBuild.rawBuild.parent.properties
    .findAll { it.value instanceof hudson.model.ParametersDefinitionProperty }
    .collectMany { it.value.parameterDefinitions }

// Create new params and merge them with existing ones
jobParams = [
    booleanParam(name: 'boolean_param', defaultValue: false)
    /* other params */
] + existing

// Create properties
properties([
    parameters(jobParams)
])

Note: But you should either run it in a non-sandboxed environment or use with @NonCPS

Using parameters with Jenkins pipeline builds, If you are using the Groovy plugin and want to leverage parameters for your get current build def build = thr?.executable // get parameters def parameters  1 Answer1. Active Oldest Votes. 1. 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 }

Parameterized System Groovy script, The parameter delay=0sec can be added to start the build immediately. hudson, now when using Jenkins I cannot add new parameters to this job anymore. Hi, I have a custom build plugin written in java and would like to use parameters  To add to @Omkar's answer, I would like to explain how to add the environment variable. Manage Jenkins - Configure System - Global properties answered Dec 10, 2018 by Zoo

Parameterized Build, This plugin allows dynamic generation of default build parameter values. (e.g. current user-name, current date/time, etc. or more complex Groovy scripts). From the "Add Parameter" drop-down menu, choose "Dynamic Choice Parameter​". Safe use of anonymous classes; Fixes in POM to allow release with maven  Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo (7) , I wrote a little groovy script which does the trick You should add a 'Dynamic Choice Parameter' to your job and customize the following groovy script to your needs : parameter example configured branches git parameters.

Dynamic Parameter Plug-in, Adds extended functionality to Choice parameter. For info on (Jan 07, 2012). Added ability to use groovy script to fetch options for parameter. This plugin allows single select and multi select build parameters to be configured. Here is a​  First, you need to define parameters for your job by selecting "This build is parameterized", then using the drop-down button to add as many parameters as you need. There are different parameter types available, and it is extensible, too. The way parameters take effect is also different depending on the parameter type you choose.

Comments
  • you can use .push instead of .add
  • parameters and properties seem to be groovy properties, so this should work: properties += [jobProperties, disable....] and parameters += newParamsList
  • I think properties block is not supported in latest version of Jenkins