Home > Net >  Iterating over groovy file contents
Iterating over groovy file contents

Time:11-05

I have two groovy scipts (executed in Jenkins pipeline), one with variables:

// Params file
PARAM1 = "1"
PARAM2 = "2"
PARAM3 = "3"
PARAM4 = "4"

return this

and the second one that loads this file and uses the params:

def load_params() {
    def parameters = load "params.groovy"
        final_parameter = ""
    
        for (parameter in parameters) {
            if(final_parameter == "") {
                final_parameter = parameter.key.toUpperCase()   "="   parameter.value
            } else {
                final_parameter = final_parameter  "&|&"   parameter.key.toUpperCase()   "="   parameter.value
            }
        }
    
        return final_parameter
    }
    
    return this

Issue is that doing the iteration over parameters is not working. The type is not a map so I cannot access variables like that.

I would use parameters.PARAM1 to handle it, but the first script is dynamic and names change so there is a need to do it without hard defining the name.

Is there any way to change/iterate the parameters to get the "key" and "values"?

CodePudding user response:

Here are a few things you can do.

Option 01: Make the Parameters a Map

This is the best solution I guess.

// Params file
parameters = [ "PARAM1": "1", "PARAM2": "2", "PARAM3": "3", "PARAM4": "4"]

return this

Option 02 : Read the Parameters as a file

Instead of loading as a Script, you can read the Params as a File, then iterate over it line-by-line and read the parameters.

Option 03: Get all the Variables defined in the current binding.

This will probably return all the variables in the current Binding, so you may have to filter out the ones you defined in the param file.

def load_params() {
    def parameters = load "params.groovy"
        final_parameter = ""
        paramMap = [:] << parameters.getBinding().getVariables()
        for (parameter in paramMap) {
            if(final_parameter == "") {
                final_parameter = parameter.key.toUpperCase()   "="   parameter.value
            } else {
                final_parameter = final_parameter  "&|&"   parameter.key.toUpperCase()   "="   parameter.value
            }
        }
    
        return final_parameter
    }
    
    return this
  • Related