【问题标题】:Setting envvars in Jenkins plugin在 Jenkins 插件中设置环境变量
【发布时间】:2025-12-17 03:30:01
【问题描述】:

我正在尝试开发新的 Jenkins 插件。我从 Jenkins 提供的 hello-world archetype 开始。我的插件工作正常!

Bun 现在我想从我的插件中放入一些环境变量。我已经使用了 whis 代码来做到这一点

public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) {

    ...
    EnvVars envVars = run.getEnvironment(listener);
    envVars.put("SOME_VARIABLE", "SOME_VALUE");
    ...

}

但它不起作用。我正在尝试在下一个构建步骤中使用此变量,但一无所获。我用谷歌搜索了它,并没有很清楚的描述。现有插件(EnvInject 等)的源代码也无济于事。

我做错了什么?谁能给我一些样品?

【问题讨论】:

    标签: java jenkins jenkins-plugins


    【解决方案1】:

    来自我的插件...

     private void putEnvVar(String key, String value) throws IOException {
         Jenkins jenkins = Jenkins.getInstance();
         DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties = jenkins.getGlobalNodeProperties();
         List<EnvironmentVariablesNodeProperty> envVarsNodePropertyList = globalNodeProperties.getAll(hudson.slaves.EnvironmentVariablesNodeProperty.class);
    
         EnvironmentVariablesNodeProperty newEnvVarsNodeProperty = null;
         EnvVars envVars = null;
    
         if (envVarsNodePropertyList == null || envVarsNodePropertyList.isEmpty()) {
            newEnvVarsNodeProperty = new hudson.slaves.EnvironmentVariablesNodeProperty();
            globalNodeProperties.add(newEnvVarsNodeProperty);
            envVars = newEnvVarsNodeProperty.getEnvVars();
         } else {
            envVars = envVarsNodePropertyList.get(0).getEnvVars();
         }
         envVars.put(key, value);
      }
    

    【讨论】: