简体   繁体   English

我可以在 Jenkins 共享库调用之间保持状态吗?

[英]Can I persist state between Jenkins shared library calls?

I would like to persist the state of some logic between calls in my Jenkins shared library.我想在我的 Jenkins 共享库中保留调用之间的某些逻辑状态。 I don't want to pass in an object/map/... with the state in the arguments but use some kind of global variable/map for this.我不想在参数中传递带有状态的对象/映射/...,而是为此使用某种全局变量/映射。 I failed with global varibales in the foobar.groovy below or use of environment variables.我在下面的 foobar.groovy 中使用全局变量或使用环境变量失败。 I found a work-around by creating a small helper class with a static map to store my data but this does not seem to be the right solution.我通过创建一个带有静态映射的小型辅助类来存储我的数据找到了一种解决方法,但这似乎不是正确的解决方案。 Is there a cleaner way?有更干净的方法吗?

src/pkg/GlobalConfig.groovy src/pkg/GlobalConfig.groovy

package pkg;

class GlobalConfig {
    // define a static map
    static Map data = new HashMap()
}

use map in shared library eg vars/foobar.groovy在共享库中使用映射,例如 vars/foobar.groovy

import pkg.GlobalConfig
 
def do_something() {
    def data = pkg.GlobalConfig.data
    // do something with data
}

Define your global variables with the @groovy.transform.Field annotation.使用@groovy.transform.Field注释定义全局变量。
Take a look at the Defining global variables section in the pipeline documentation.查看管道文档中的定义全局变量部分。

foobar.groovy can look like: foobar.groovy看起来像:

import groovy.transform.Field

@Field
def data = [:]

def do_something() {
   // use data as is
}

From outside this file just use foobar.data .在这个文件之外,只需使用foobar.data
Once the library is loaded the state will be persistent whenever you use it.加载库后,无论何时使用它,状态都将是持久的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM