简体   繁体   English

传递变量 beetwen groovy 文件

[英]passing variables beetwen groovy files

I'm managing many jobs in Jenkins by DSL plugin.我正在通过 DSL 插件管理 Jenkins 中的许多工作。 That plugin is using.groovy definitions so I think even if someone doesn't use Jenkins but using groovy may be able to help.该插件正在使用.groovy 定义,所以我认为即使有人不使用 Jenkins 但使用 groovy 可能会有所帮助。

Generally, I want to create an additional file, that may be a groovy file, JSON or YAML, whatever.通常,我想创建一个附加文件,可能是 groovy 文件、JSON 或 YAML 等。 It important is the possibility to connect that file with my.groovy file.重要的是可以将该文件与 my.groovy 文件连接起来。

In that file, I'm defining variables(rather just strings) for example address IP or other stuff eg.在该文件中,我正在定义变量(而只是字符串),例如地址 IP 或其他东西,例如。

ip_gitlab: 1.2.3.4
default_user: admin

In my groovy files, I want to be able to use these variables.在我的 groovy 文件中,我希望能够使用这些变量。

That approach is possible in groovy?这种方法在 groovy 中可行吗?

I suggest use a property file as @JBaruch wrote我建议使用@JBaruch 写的属性文件

ip_gitlab=1.2.3.4
default_user=admin

And load it并加载它

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

Then you can use it, get ip for example:然后就可以使用了,例如得到ip:

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

Make groovy file and define some general information and use load .制作 groovy 文件并定义一些一般信息和使用load

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

build_name = 'hello'

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

And use it by load并通过load使用它

load 'hello.conf'

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

For given test.properties file:对于给定test.properties文件:

ip_gitlab=1.2.3.4
default_user=admin

Load and check:加载并检查:

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

def ip= 'ip_gitlab'
assert properties."$ip" == '1.2.3.4'

if you want a Jenkins specific answer: There's a Config File Provider Plugin to jenkins.如果您想要 Jenkins 特定答案:jenkins 有一个配置文件提供程序插件

You can store config/properties files via Managed files.您可以通过托管文件存储配置/属性文件。 Go to Manage Jenkins>Managed files and and create a new file. Go 管理 Jenkins>Managed files 并创建一个新文件。 It supports.groovy, .json, .xml and many others.它支持.groovy、.json、.xml等。

Once you have that, you can load the said file inside a job using the Provide Config file checkbox which will load the file into an env variable automatically.完成后,您可以使用提供配置文件复选框将所述文件加载到作业中,该复选框会自动将文件加载到环境变量中。

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

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