jenkins pipelines:shell脚本无法获取更新的环境变量

2024-02-21

在 Jenkins 中,我想获取用户输入并传递给 shell 脚本以供进一步使用。
我尝试设置为环境变量,但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

            }
        }
    }
}

我们在管道脚本中设置的环境变量只能在脚本内访问。因此,即使您将变量声明为全局变量,它也无法在 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,

"

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jenkins pipelines:shell脚本无法获取更新的环境变量 的相关文章

随机推荐