【问题标题】:jenkins pipelines: shell script cannot get the updated environment variable詹金斯管道:shell脚本无法获取更新的环境变量
【发布时间】:2018-02-13 06:54:59
【问题描述】:

在 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 jenkins jenkins-pipeline


    【解决方案1】:

    您需要将阶段之间的变量作为环境变量传递,例如像这样:

    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}"
        }
    }
    

    【讨论】:

    • 是的,因为这种替换只适用于 Groovy,不适用于 shell 代码。在您的 shell 脚本中,您应该能够像 echo $MY_VAR 一样直接使用该变量。
    【解决方案2】:

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

    "

    【讨论】:

    • 我试过了,参数通过了,而我的参数是一个映射,例如[fristPara:100, secondPaa:abc]。请问我怎样才能得到它并在shell脚本中分成2个变量?
    • 已添加shell脚本以供参考,如果您能接受答案,那就太好了,因为这回答了您的问题
    • 谢谢,它可以工作,但设置为环境变量更适合我的情况。我对此表示赞成=]
    【解决方案3】:

    您必须在全局范围内声明变量,以便两个地方引用同一个实例。

    def myVal
    
    pipeline { ... }
    

    【讨论】:

    • 试过 def test="wfe";在管道前面,并在 shell 脚本中回显“${test}”,但它输出 null
    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多