Jenkins-将参数传递给groovy函数
我一直在尝试用管道内部的参数调用另一个常规函数,但没有任何运气.
我将参数传递给的常规函数包含一个bash脚本,但是此bash脚本无法识别我传递给它的参数.但是,如果我传递的参数在管道中定义为parameters {}
,那么它可以工作,但我不希望这样做.
I've been trying to call another groovy function with parameters inside my pipeline without any luck.
The groovy function I am passing the parameters to consists of a bash script, but this bash script does not recognize the parameter(s) I am passing to it. If however the parameter passed by i defined as a parameters {}
in the pipeline, then it works, but I do not want this.
问题:
Shell脚本无法识别/理解参数,变量为空,没有值.
PROBLEM:
The shell script does not recognize/understand the arguments, the variables are empty, no value.
pipelineJenkins.groovy
def call {
pipeline {
parameters {
string (name: VAR1, defaultValue: "Peace", description: '' } <--- This works, but not beneficial
string (name: VAR2, defaultValue: "Space", description: '' } <--- This works, but not beneficial
stages {
stage ('Run script') {
steps {
groovyFunction("${VAR1}", "${VAR2}")
groovyFunction("Peace", "Space") <--- WHAT I WANT
}
}
}
}
}
groovyFunction.groovy
def call(var1, var2) {
sh 'echo MY values ${var1} and ${var2}'
sh "echo MY values ${var1} and ${var2}" <-- Works using double quotes, this messes up sed and for-loops...
}
具有参数的管道输出:
MY values Peace and Space
没有参数的管道输出:
MY values and
我曾尝试使用上一个问题中建议的environment{}
关键字,但没有任何运气. 詹金斯-环境
I have tried using the environment{}
keyword as suggested in my previous question, without any luck. Jenkins - environment
我知道那里也有类似的问题:
I am aware that there are similar issues out there:
- Pass groovy variable to shell script
- How to assign groovy variable to shell variable
- Jenkins parameters
注意: 这与我的问题 Shell参数Jenkins
谢谢.
更新
我已经更新了使用环境变量而不使用environment {}
I have updated the answer to use environment variable without having environment {}
使用我在这里使用过的环境变量(我对您的代码进行了一些重构):
Use environment variables like the ones i have used here (i refactored your code a little bit):
def callfunc() {
sh 'echo MY values $VARENV1 and $VARENV2'
}
pipeline {
agent { label 'agent_1' }
stages {
stage ('Run script') {
steps {
script {
env.VARENV1 = "Peace"
env.VARENV2 = "Space"
}
callfunc()
}
}
}
}
env.VARENV1
和env.VARENV2
是我在script{}
内部使用的环境变量.您可以为其分配值.
env.VARENV1
and env.VARENV2
are the environment variables i have used here inside script{}
. You can assign values to them.
这是我的新输出:
我真的希望它能帮上忙.
I really hope it helped.
使用环的更新
使用shell脚本的三重单引号引起循环并向其中添加grrovy变量:
Using triple single quotes for shell script for loop and adding grrovy variable to it:
def callfunc() {
sh '''
export s="key"
echo $s
for i in $VARENV1
do
echo "Looping ... i is set to $i"
done
'''
}
pipeline {
agent { label 'agent_1' }
stages {
stage ('Run script') {
steps {
script {
env.VARENV1 = "Peace"
}
callfunc()
}
}
}
}
输出: