[英]Set environment variables from Groovy script in Jenkins
I have got a FreeStyle project in Jenkins.我在 Jenkins 有一个 FreeStyle 项目。 One part of the build is an "Execute Groovy script" build step (important: not an 'Execute System Groovy script' step - that would not work).
构建的一个部分是“执行 Groovy 脚本”构建步骤(重要的是:不是“执行系统Groovy 脚本”步骤——那是行不通的)。
The calculations the script does are needed later on in other build stepes.稍后在其他构建步骤中需要脚本执行的计算。 How can I use variables along all steps?
如何在所有步骤中使用变量? Is there a possibility to set environment variables in the "Execute Groovy script" that will be extracted later?
是否有可能在稍后提取的“执行 Groovy 脚本”中设置环境变量?
I already tried to use我已经尝试使用
import hudson.EnvVars
import hudson.model.*;
...
def envvars = ['envVarName': 'envVarValue']
build.environments.add(0, Environment.create(new EnvVars(envvars)))
but 'build' cannot be found in non-system groovy steps.但是在非系统常规步骤中找不到“构建”。
Any ideas?有任何想法吗?
Thanks a lot :) ian非常感谢:) 伊恩
The execute groovy script step simply runs a groovy script on the agent.执行 groovy 脚本步骤只是在代理上运行一个 groovy 脚本。 It is the same idea as running a shell script on the agent: it's not running in the Jenkins master, so there is no concept of a Jenkins build environment.
它与在代理上运行 shell 脚本的想法相同:它不在 Jenkins master 中运行,因此没有 Jenkins 构建环境的概念。 If you want this step to pass information to a next one, the easiest is probably to write the values you want to share to a file in the workspace.
如果您希望此步骤将信息传递给下一个步骤,最简单的方法可能是将要共享的值写入工作区中的文件。
Create a parameter action for the current thread.为当前线程创建一个参数操作。
Or you can create a global environment variable witten here .或者您可以在此处创建一个全局环境变量。
import hudson.EnvVars;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.util.DescribableList;
import jenkins.model.Jenkins;
public createGlobalEnvironmentVariables(String key, String value){
Jenkins instance = Jenkins.getInstance();
DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = instance.getGlobalNodeProperties();
List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(EnvironmentVariablesNodeProperty.class);
EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
EnvVars envVars = null;
if ( envVarsNodePropertyList == null || envVarsNodePropertyList.size() == 0 ) {
newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
globalNodeProperties.add(newEnvVarsNodeProperty);
envVars = newEnvVarsNodeProperty.getEnvVars();
} else {
envVars = envVarsNodePropertyList.get(0).getEnvVars();
}
envVars.put(key, value)
instance.save()
}
createGlobalEnvironmentVariables('Var1','Dummy')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.