使用groovy为jenkins作业添加一个额外的参数

时间:2018-02-23 16:39:17

标签: jenkins groovy jenkins-pipeline

我们的用户在jenkins文件中调用了一组groovy脚本,这些脚本设置了一些常见的作业属性。但是,在我们进行此次更新时,我们无法弄清楚如何保留现有参数。

我们的常规代码片段:

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,
  ])

但是,这会覆盖参数定义,因此如果用户在调用我们的groovy之前在其jenkins文件中指定了不同的参数定义,那么它就会被删除。

我可以使用currentBuild.rawBuild.getAction(ParametersAction)访问现有参数,但是如果我理解正确,我需要ParameterDefinition而不是ParameterValue才能设置属性。我试过currentBuild.rawBuild.getAction(ParametersDefinitionProperty.class),我认为我可以使用它像ParametersAction,但它返回null。

是否可以从Jenkins文件中调用groovy中的参数定义?或者是否有一种不同的方式可以让我们在作业中添加一个额外的参数而不会消除当前在jenkinsfile中定义的现有参数?

4 个答案:

答案 0 :(得分:1)

所以我们这样做的方式就是将它们视为一个简单的列表,然后将它们连接在一起。所以jenkinsfile首先从共享库中获取一个列表,然后将它们自己添加到列表中,然后设置params(不是共享库)

Repos jenkinsfiles这样做:

#!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

我们的共享库如下所示:

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
}

答案 1 :(得分:1)

我们执行了以下常规代码来检索参数定义并将新参数添加到现有参数中(我们不了解用户将把什么作为参数)。如果您有更简单的方法,我接受:

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

答案 2 :(得分:0)

我认为您也可以执行以下操作:

// 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)
])

注意:但是您应该在非沙盒环境中运行它,或者与@NonCPS一起使用

答案 3 :(得分:0)

有一个示例如何将其他字符串参数NEW_PARAM添加到名称为test的作业中:

job = Jenkins.instance.getJob("test")

ParametersDefinitionProperty params = job.getProperty(ParametersDefinitionProperty.class);

List<ParameterDefinition> newParams = new ArrayList<>();
newParams.addAll(params.getParameterDefinitions());
newParams.add(new StringParameterDefinition("NEW_PARAM", "default_value"));
job.removeProperty(params);
job.addProperty(new ParametersDefinitionProperty(newParams));