您如何处理声明性管道中的全局变量? [英] How do you handle global variables in a declarative pipeline?

查看:15
本文介绍了您如何处理声明性管道中的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前问了一个问题关于如何覆盖变量在环境指令中定义,这似乎是不可能的.

Previously asked a question about how to overwrite variables defined in an environment directive and it seems that's not possible.

我想在一个阶段设置一个变量,并让其他阶段可以访问它.在声明式管道中,执行此操作的唯一方法似乎是在脚本块中.

I want to set a variable in one stage and have it accessible to other stages. In a declarative pipeline it seems the only way to do this is in a script{} block.

例如,我需要在结帐后设置一些变量.因此,在结帐阶段结束时,我有一个脚本{} 块来设置这些变量,并且它们可以在其他阶段访问.

For example I need to set some vars after checkout. So at the end of the checkout stage I have a script{} block that sets those vars and they are accessible in other stages.

这行得通,但感觉不对.为了便于阅读,我更喜欢在管道顶部声明这些变量并覆盖它们.因此,这意味着在开始时有一个设置变量"阶段,其中包含一个仅定义 vars 的脚本块——这很难看.

This works, but it feels wrong. And for the sake of readability I'd much prefer to declare these variables at the top of the pipeline and have them overwritten. So that would mean having a "set variables" stage at the beginning with a script{} block that just defines vars- thats ugly.

我很确定我在这里遗漏了一个明显的功能.声明式管道是否具有全局变量功能或者我必须使用脚本{}

I'm pretty sure I'm missing an obvious feature here. Do declarative pipelines have a global variable feature or must I use script{}

推荐答案

就像@mkobit 所说,您可以将变量定义到管道块之外的全局级别.你试过吗?

Like @mkobit says, you can define the variable to global level out of pipeline block. Have you tried that?

def my_var
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                my_var = 'value1'
            }
        }

        stage('Example2') {
            steps {
                printl(my_var)
            }
        }

    }
}

这篇关于您如何处理声明性管道中的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆