1

I want define a variable in groovy with where the variable name is passed by another variable.

Something like.

def runExtFunc(varName){
    def varName  // => def abc
    varName = load 'someFile.groovy'   // abc = load 'someFile.groovy'

    varName."$varName"() // -> abc.abc() (run function defined in File)
}

    [...]
runExtFunc('abc')  // -> abc.abc() (Function abc defined in File)
    [...]
runExtFunc('xyz')  // -> xyz.xyz() (Function xyz defined in File)
    [...]

Sadly def varName defines the variable varName and not abc. When I call runExtFunc twice an error occoures bacause varName is already defined.

I also tried

def runExtFunc(varName){
    def "${varName}"  // => def abc
       [...]
    "${varName}" =  load 'someFile.groovy'
       [...]
}

which doesn't work either.

Any suggestions?

2
  • Can you give an example of why you want this? Your first code should just work with varName, and I can't see why you'd want to name a locally scoped variable? Commented Jun 16, 2016 at 10:51
  • Refer to this link stackoverflow.com/questions/6729605/… Commented Jun 16, 2016 at 11:14

4 Answers 4

1

This is the wrong approach. Normally you would use List, Map or Set data structures, which allow you to save a collection and access specific elements in the collection.

List allows you to hold specific values (unique or non-unique). Set allows you to hold specific values (all unique). Map allows you to have Key, Value pairs (Key must be unique) .

Read more here groovy list, groovy map

Sign up to request clarification or add additional context in comments.

Comments

0

Try this (if I understand you correctly):

def dummyFunc(varName) {
  new GroovyShell(this.binding).evaluate("${varName}")
}

dummyFunc('abc')

abc = "Hello there"
println abc

Prints

Hello there

1 Comment

trying this approach but getting following error in jenkinsfile, any suggestions, THe error is Groovy.lang.MissingFieldException: No such field: binding for class: WorkflowScript
0

See here https://godless-internets.org/2020/02/14/extracting-jenkins-credentials-for-use-in-another-place/

secret_var="SECRET_VALUE_${secret_index}" aws ssm put-parameter --name ${param_arn} --type "SecureString" --value ${!secret_var} --region us-east-2 --overwrite

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

I'm entering here a code sample we've done.

Please, feel free to comment.

http://groovy-lang.org/syntax.html https://godless-internets.org/2020/02/14/extracting-jenkins-credentials-for-use-in-another-place/

def int fileContentReplaceDynamic(String filePathVar, String envTail = "", 
String [] keysToIgnore = new String[0]){

def filePath = readFile filePathVar
def lines = filePath.readLines()

//def regex = ~/\b__\w*\b/
String regex = "__(.*?)__"
ArrayList credentialsList = new ArrayList();
ArrayList<String> keysToIgnoreList = new ArrayList<String>(Arrays.asList(keysToIgnore));

for (line in lines){
    Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
    Matcher matcher = pattern.matcher(line)

    while (matcher.find()){
        String credKeyName = matcher.group().replaceAll("__","")
        if ((! credentialsList.contains(credKeyName)) && 
            (! keysToIgnoreList.contains(credKeyName))) {
            credentialsList.add(credKeyName)
        } else {
            log.info("Credencial ignorada o ya incluida: ${credKeyName}")
        }
    }       
}


if(credentialsList.size() <= 0){
    log.info("No hay variables para aplicar transformada")
    return 0
}

log.info("Numero de credenciales encontradas a sustituir: " + credentialsList.size())
String credentialsListString = String.join(", ", credentialsList);
log.info("Credenciales: " + credentialsListString)

def credsRequest = null
for(def credKeyName in credentialsList){
    // Retrieve the values of the variables by environment tail name.
    String credKeyNameByEnv = "${credKeyName}";
    if ((envTail != null) && (! envTail.trim().isEmpty())) {
        credKeyNameByEnv = credKeyNameByEnv + "-" + envTail.trim().toUpperCase();
    }
    
    // Now define the name of the variable we'll use
    // List<org.jenkinsci.plugins.credentialsbinding.MultiBinding>
    // Tip: java.lang.ClassCastException: 
    // org.jenkinsci.plugins.credentialsbinding.impl.BindingStep.bindings 
    // expects class org.jenkinsci.plugins.credentialsbinding.MultiBinding
    String varName = "var_${credKeyNameByEnv}"
    if (credsRequest == null) {
        // Initialize
        credsRequest = [string(credentialsId: "${credKeyNameByEnv}", variable: "${varName}")]
    } else {
        // Add element
        credsRequest << string(credentialsId: "${credKeyNameByEnv}", variable: "${varName}")
    }
}

int credsProcessed = 0
def passwordsRequest = null
StringBuilder sedReplacements = new StringBuilder();

// Now ask jenkins to fill in all variables with values
withCredentials(credsRequest) {
    for(def credKeyName in credentialsList){
        String credKeyVar = "var_${credKeyName}"
        log.info("Replacing value for credential ${credKeyName} stored in ${credKeyVar}")
        
        String credKeyValueIn = "${!credKeyVar}"
        String credKeyValue = null;
        if ("empty_string_value".equals(credKeyValueIn.trim())) {
            credKeyValue = "";
        } else {
            credKeyValue = credKeyValueIn.replaceAll(/(!|"|@|#|\$|%|&|\/|\(|\)|=|\?)/, /\\$0/)
        }
        
        if (passwordsRequest == null) {
            // Initialize
            passwordsRequest = [[password: "${credKeyValue}" ]]
        } else {
            // Add element
            passwordsRequest << [password: "${credKeyValue}" ]
        }
        
        sedReplacements.append("s/__${credKeyName}__/${credKeyValue}/; ")
        
        credsProcessed++
    }
}

wrap([$class: "MaskPasswordsBuildWrapper", varPasswordPairs: passwordsRequest ]){
    
    String sedReplacementsString = sedReplacements.toString().trim();
    if (sedReplacementsString.endsWith(";")) {
        sedReplacementsString = sedReplacementsString.substring(0, sedReplacementsString.length() -1);
        sedReplacementsString = sedReplacementsString + "g;"
    }
    
    sh """sed -i "${sedReplacementsString}" ${filePathVar}"""
}

log.info("Finaliza la transformada. Transformados: ${credsProcessed}/${credentialsList.size()} ")

if (credsProcessed != credentialsList.size()) {
    log.info("Hay credenciales que no se han podido encontrar en el vault de Jenkins.")
    log.info("Si estas guardando cadenas vacias en credenciales, guarda en su lugar el valor 'empty_string_value'.");
    return -1
}
return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.