jenkins管道:shell脚本无法获取更新的环境变量
在Jenkins中,我希望获得一个用户输入并传递给shell脚本以供进一步使用。jenkins管道:shell脚本无法获取更新的环境变量,shell,jenkins,jenkins-pipeline,Shell,Jenkins,Jenkins Pipeline,在Jenkins中,我希望获得一个用户输入并传递给shell脚本以供进一步使用。 我试图设置为环境变量,但shell脚本无法获取最新值,旧值为echo pipeline { agent none environment{ myVar='something_default' } stages { stage('First stage') { agent none steps{
我试图设置为环境变量,但shell脚本无法获取最新值,旧值为echo
pipeline {
agent none
environment{
myVar='something_default'
}
stages {
stage('First stage') {
agent none
steps{
echo "update myVar by user input"
script {
test = input message: 'Hello',
ok: 'Proceed?',
parameters: [
string(name: 'input', defaultValue: 'update it!', description: '')
]
myVar = "${test['input']}"
}
echo "${myVar}" // value is updated
}
}
stage('stage 2') {
agent any
steps{
echo "${myVar}" // try to see can myVar pass between stage and it output expected value
sh("./someShell.sh") // the script just contain a echo e.g. echo "myVar is ${myVar}"
// it echo the old value. i.e.something_default
}
}
}
}
您必须在全局范围上声明变量,以便两个位置都引用同一个实例
def myVal
pipeline { ... }
我们在管道脚本中设置的环境变量只能在脚本中访问。因此,即使您将变量声明为全局变量,它也不会在shell脚本中工作 我可以考虑的唯一选项是,将其作为参数传递给shell脚本
sh("./someShell.sh ${myVar}")
编辑:
根据OP对用于解析输入的Shell脚本的查询更新了答案
LINE="[fristPara:100, secondPaa:abc]"
LINE=$(echo $LINE | sed 's/\[//g')
LINE=$(echo $LINE | sed 's/\]//g')
while read -d, -r pair; do
IFS=':' read -r key val <<<"$pair"
echo "$key = $val"
done <<<"$LINE,
LINE=“[fristPara:100,secondPaa:abc]”
LINE=$(echo$LINE | sed's/\[//g')
LINE=$(echo$LINE | sed's/\]//g')
当读取-d,-r对时;做
IFS=':'read-r key val您需要在阶段之间将变量作为环境变量传递,例如:
stage("As user for input") {
steps {
env.DO_SOMETING = input (...)
env.MY_VAR = ...
}
}
stage("Do something") {
when { environment name: 'DO_SOMETING', value: 'yes' }
steps {
echo "DO_SOMETING has the value ${env.DO_SOMETHING}"
echo "MY_VAR has the value ${env.MY_VAR}"
}
}
已尝试def test=“wfe”;在管道前面,在shell脚本echo“${test}”中,但它输出null,我尝试了并传递了参数,而我的参数是一个映射,例如[fristPara:100,secondPaa:abc]。我可以问一下如何在shell脚本中获得它并将其分为2个变量吗?添加了shell脚本以供参考,如果您可以接受答案,这将是非常好的,因为这回答了您的问题谢谢,它可以工作,但设置为环境变量对我的情况更有效。相反,我对它投赞成票=]是的,因为这种替换只在Groovy中有效,而不在shell代码中有效。在shell脚本中,应该能够直接使用变量,如echo$MY_VAR。