[英]Groovy - Define variable where the variable name is passed by another variable
I want define a variable in groovy with where the variable name is passed by another variable.我想在 groovy 中定义一个变量,其中变量名由另一个变量传递。
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.可悲的是 def varName 定义了变量 varName 而不是 abc。 When I call runExtFunc twice an error occoures bacause varName is already defined.
当我两次调用 runExtFunc 时,会发生错误,因为 varName 已经定义。
I also tried我也试过
def runExtFunc(varName){
def "${varName}" // => def abc
[...]
"${varName}" = load 'someFile.groovy'
[...]
}
which doesn't work either.这也不起作用。
Any suggestions?有什么建议?
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 , Map或Set数据结构,这使您可以保存集合并访问集合中的特定元素。
List allows you to hold specific values (unique or non-unique). 列表允许您保存特定的值(唯一或不唯一)。 Set allows you to hold specific values (all unique).
Set可让您保留特定值(所有值都是唯一的)。 Map allows you to have
Key, Value
pairs (Key must be unique) . Map允许您具有
Key, Value
对(键必须是唯一的)。
Read more here groovy list , groovy map 在此处阅读更多内容常规列表 常规地图
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
See here https://godless-internets.org/2020/02/14/extracting-jenkins-credentials-for-use-in-another-place/请参阅此处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 secret_var="SECRET_VALUE_${secret_index}" aws ssm put-parameter --name ${param_arn} --type "SecureString" --value ${!secret_var} --region us-east-2 --overwrite
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/ 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;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.