使用Groovy方法变量的Jenkins管道中的动态变量 [英] Dynamic variable in Jenkins pipeline with groovy method variable
问题描述
我在Groovy中有一个用于声明性管道的Jenkins文件,并且创建了两个名为OCP_TOKEN_VALUE_ONE和OCP_TOKEN_VALUE_TWO的Jenkins变量以及相应的值.当我尝试传递方法变量并在sh命令中使用它时,问题就来了.
I have a Jenkinsfile in Groovy for a declarative pipeline and two created Jenkins variables with names OCP_TOKEN_VALUE_ONE and OCP_TOKEN_VALUE_TWO and the corresponding values. The problem comes when I try to pass a method variable and use it in an sh command.
我有下一个代码:
private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
sh """/opt/ose/oc login ${OCP_URL} --token=${openshiftNamespaceGroupToken} --namespace=${projectProps.namespace}-${environment}"""
}
问题是,方法deployToOpenShift
在openshiftNamespaceGroupToken
变量中具有一个值,该值是在Jenkins中设置的变量的名称.它必须是动态的,问题在于Jenkins不会解析Jenkins变量值,只是将其作为String传递了,我的意思是,结果是:
The problem is, the method deployToOpenShift
has in the openshiftNamespaceGroupToken
variable, a value that is the name of variable that has been set in Jenkins. It needs to be dynamic and the problem is that Jenkins don't resolve the Jenkins variable value, just the one passed as String, I mean, the result is:
-token = OCP_TOKEN_VALUE_ONE
--token=OCP_TOKEN_VALUE_ONE
如果我输入代码
private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
sh """/opt/ose/oc login ${OCP_URL} --token=${OCP_TOKEN_VALUE_ONE} --namespace=${projectProps.namespace}-${environment}"""
}
工作完美,但不是动态的,这是方法变量的重点.如您所见,我已经尝试使用"东西,但是没有用.
works perfect but is not dynamic that is the point of the method variable. I have tried with the """ stuff as you can see, but not working.
还有其他想法吗?
已编辑,其中包含调用该方法的代码:
Edited with the code that calls the method:
...
projectProps = readProperties file: './gradle.properties'
openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()
...
stage ('Deploy-Dev') {
agent any
steps {
milestone ordinal : 10, label: "Deploy-Dev Milestone"
deployToOpenShift(projectProps, 'dev', openShiftTokenByGroup)
}
}
推荐答案
我有两种不同的方法可以做到这一点.一种是从groovy中使用evaluate
这样的:
I have got two different ways to do that. One is using evaluate
from groovy like this:
def openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()
evaluate("${openShiftTokenByGroup}") //This will resolve the configured value in Jenkins
第二种方法是相同的,但是在sh命令中,使用eval
将$字符转义:
The second one is the same approach but in the sh command with eval
escaping the $ character:
sh """
eval \$$openShiftTokenByGroup
echo "Token: $openShiftTokenByGroup
"""
这也将起到神奇作用,您将获得Jenkins的配置值.
This will do the magic too and you'll get the Jenkins configured value.
这篇关于使用Groovy方法变量的Jenkins管道中的动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!