问题
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. 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.
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
.
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. 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?
回答1:
You can retrieve the build environment — an EnvVars
object — which has a convenience method expand(String).
This recognises $VARIABLE
and ${VARIABLE}
-style strings and substitutes in the corresponding value from the environment.
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);
...
}
来源:https://stackoverflow.com/questions/30512887/variable-substitution-in-jenkins-plugin