如何从单个 sh 脚本输出定义多个环境变量

5 groovy jenkins-pipeline

我需要在 sh 块中执行一个设置多个环境变量的工具。然后,我需要将这些环境变量从 sh 步骤导出到 withEnv 步骤中,以便可用于另一个步骤。

我知道我可以通过在同一个 sh 块中执行该工具和 ansible 来完成类似的事情。如果可能的话,我想利用 ansiblePlaybook 插件来完成此任务。

stage('Example') {
    steps {
        // Run the tool that generates the eval block
        sh 'some-tool'
        // Generates output like:
        // TOKENA='foo'; TOKENB='bar'; export TOKENA; export TOKENB; echo "success"

        // This is where I need help. 
        // How to translate the script output from above into variables
        // So that I can make them available to the ansiblePlaybook step.
        withEnv([TOKENA=TOKENA, TOKENB=TOKENB]) {
            ansiblePlaybook( 
                // ... irrelevant details
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我提供的代码不完整。我不期望它有任何结果。

sel*_*nin 6

我最近遇到了同样的问题,需要使用 JenkinswithEnv块保存多个环境变量。这对我有用:

    stage('Do some hard work'){
        steps {
            withEnv(["MY_VAR_1=${VALUE_1}", "MY_VAR_2=${VALUE_2}"]) {
                script {
                    bat (
                            script: 'echo "Doing some Hard work with ${MY_VAR_1} and ${MY_VAR_2}"'
                    )
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


dag*_*ett 1

你拥有的一切都是外壳。包括来自 的输出some-tool

那么为什么不把这个放进some-tool去呢ansible

但是,如果您可以将some-tool输出仅作为标记分配,那么以下代码将起作用

def env = new ConfigSlurper().parse(" TOKENA='foo'; TOKENB='bar'; ")
Run Code Online (Sandbox Code Playgroud)