【问题标题】:passing variables beetwen groovy files传递变量 beetwen groovy 文件
【发布时间】:2020-02-06 21:18:16
【问题描述】:

我通过 DSL 插件在 Jenkins 中管理许多工作。该插件使用 .groovy 定义,所以我认为即使有人不使用 Jenkins 但使用 groovy 也可能会有所帮助。

一般来说,我想创建一个附加文件,它可能是一个 groovy 文件、JSON 或 YAML 等等。重要的是可以将该文件与我的 .groovy 文件连接起来。

在该文件中,我正在定义变量(而只是字符串),例如地址 IP 或其他内容 例如。

ip_gitlab: 1.2.3.4
default_user: admin

在我的 groovy 文件中,我希望能够使用这些变量。

这种方法在 groovy 中可行吗?

【问题讨论】:

  • 当然可以。例如有groovy-lang.org/json.html
  • 如果可以在 DSL 插件中定义额外的类路径。然后放入您将添加到类路径 groovy 文件(如class GLOBAL{ def a=111; def b=222; })的文件夹中。然后在代码中你应该能够访问它GLOBAL.a
  • @daggett 我正在尝试你写的,但我总是遇到错误:org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'org.codehaus.groovy.runtime.InvokerHelper$1@641eff69' with class 'org.codehaus.groovy.runtime.InvokerHelper$1' to class 'javaposse.jobdsl.dsl.JobParent' 这个错误发生在处理你的类 GLOBAL 期间
  • 我忘了。对于每个定义的变量,应该有 static 前缀。 class GLOBAL{ static def a=111; static def b=222; }。但是您遇到的错误很奇怪。你能显示你声明的变量以及你如何在 dsl 中使用它吗?
  • 1.我的dsl配置postimg.cc/TLHK5k6h 2. dsl处理时出错postimg.cc/21F37jDs

标签: java jenkins groovy dsl


【解决方案1】:

如果您想要 Jenkins 特定的答案: 詹金斯有一个Config File Provider Plugin

您可以通过托管文件存储配置/属性文件。 转到 Manage Jenkins>Managed files 并创建一个新文件。它支持 .groovy、.json、.xml 和许多其他格式。

完成后,您可以使用提供配置文件复选框将所述文件加载到作业中,该复选框会自动将文件加载到环境变量中。

【讨论】:

    【解决方案2】:

    我建议使用@JBaruch 所写的property file

    ip_gitlab=1.2.3.4
    default_user=admin
    

    并加载它

    Properties properties = new Properties()
    File propertiesFile = new File('test.properties')
    propertiesFile.withInputStream {
        properties.load(it)
    }
    

    然后就可以使用了,比如获取ip:

    def ipPropertyName= 'ip_gitlab'
    properties."$ipPropertyName"
    

    【讨论】:

    • 这是另一个帖子的最低属性副本;您至少想关注referencing guidelines 并命名作者。
    • 不幸的是,这在 Jenkins DSL 中不起作用,找不到具有属性的文件,但是这个文件是同一个文件夹...FATAL: test.properties (No such file or directory) java.io.FileNotFoundException: test.properties (No such file or directory)
    • @rafal1337 您是否尝试使用文件的部分/完整路径?
    • @user7294900 是的,我尝试了多条路径但没有积极效果。
    【解决方案3】:

    制作 groovy 文件并定义一些一般信息并使用load

    例如,hello.conf(由 groovy 编写)

    build_name = 'hello'
    
    build_config = [
        'git': 'your git repository',
        'build_job': ['bulid_a', 'build_b']
    ]
    

    并通过load使用它

    load 'hello.conf'
    
    println(build_name)
    for (job in build_config['build_job']) {
        build job: job
    }
    

    【讨论】:

    • 看起来不错,但在 Jenkins 的 DSL 插件中不起作用:ERROR: (pipeline.groovy, line 1) No signature of method: pipeline.load() is applicable for argument types: (java.lang.String) values: [a_test.groovy]Possible solutions: job(java.lang.String), find(), folder(java.lang.String), job(java.lang.String, groovy.lang.Closure), find(groovy.lang.Closure), wait()
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多