简体   繁体   English

Jenkins插件中的变量替换

[英]Variable substitution in Jenkins plugin

I am developing a new Jenkins plugin that will be executed during the build phase of a Jenkins job and have a requirement to allow the user to specify a variable name (as opposed to a literal value) in the job configuration for the plugin. 我正在开发一个新的Jenkins插件,该插件将在Jenkins作业的构建阶段执行,并且要求允许用户在插件的作业配置中指定变量名称(而不是文字值)。 The intention is that when the job executes the variable name specified by the user will then be substituted with the real value associated with the variable and that the plugin will then use this real value when running the perform method. 目的是当作业执行时,用户指定的变量名称将替换为与变量关联的实际值,然后插件将在运行perform方法时使用此实际值。

For example if the variable MY_VARIABLE with the value myValue was injected into the build environment by another part of job and the value ${MY_VARIABLE} was specified in the job configuration for my plugin, then I would like the plugin to substitute ${MY_VARIABLE} with the real value for the variable which is myValue . 例如,如果具有值myValue的变量MY_VARIABLE被作业的另一部分注入到构建环境中,并且在我的插件的作业配置中指定了值${MY_VARIABLE} ,那么我希望该插件替换${MY_VARIABLE}使用myValue变量的实际值。

在此输入图像描述

Having done some research I understand that Jenkins does not automatically substitute variable in the job configuration for their respective values and this must be handled by the plugin. 做了一些研究后,我了解Jenkins不会自动将作业配置中的变量替换为各自的值,这必须由插件处理。 What I haven't been able to work out is the best way to perform the substitution in my plugin. 我无法解决的是在我的插件中执行替换的最佳方法。 The only solution I've found so far is the parse the string passed from the job configuration to see whether it matches the correct pattern for a variable and then lookup the value in my code. 到目前为止我找到的唯一解决方案是解析从作业配置传递的字符串,看它是否与变量的正确模式匹配,然后在我的代码中查找值。

My question is does the Jenkins API provide a better solution that would allow my plugin to substitute a variable with a real value? 我的问题是Jenkins API是否提供了一个更好的解决方案,允许我的插件替换具有实际值的变量?

You can retrieve the build environment — an EnvVars object — which has a convenience method expand(String) . 您可以检索构建环境 - 一个EnvVars对象 - 它有一个方便的方法expand(String)

This recognises $VARIABLE and ${VARIABLE} -style strings and substitutes in the corresponding value from the environment. 这可识别$VARIABLE${VARIABLE}样式的字符串,并替换来自环境的相应值。

For example: 例如:

@Override
public boolean perform(AbstractBuild build, Launcher launcher,
  BuildListener listener) throws IOException, InterruptedException {
    ...
    final EnvVars env = build.getEnvironment(listener);
    String expandedDbUrl = env.expand(dbUrl);
    ...
}

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

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