簡體   English   中英

從 Jenkins 中的 Groovy 腳本設置環境變量

[英]Set environment variables from Groovy script in Jenkins

我在 Jenkins 有一個 FreeStyle 項目。 構建的一個部分是“執行 Groovy 腳本”構建步驟(重要的是:不是“執行系統Groovy 腳本”步驟——那是行不通的)。

稍后在其他構建步驟中需要腳本執行的計算。 如何在所有步驟中使用變量? 是否有可能在稍后提取的“執行 Groovy 腳本”中設置環境變量?

我已經嘗試使用

import hudson.EnvVars
import hudson.model.*;
...
def envvars = ['envVarName': 'envVarValue']
build.environments.add(0, Environment.create(new EnvVars(envvars)))

但是在非系統常規步驟中找不到“構建”。

有任何想法嗎?

非常感謝:) 伊恩

執行 groovy 腳本步驟只是在代理上運行一個 groovy 腳本。 它與在代理上運行 shell 腳本的想法相同:它不在 Jenkins master 中運行,因此沒有 Jenkins 構建環境的概念。 如果您希望此步驟將信息傳遞給下一個步驟,最簡單的方法可能是將要共享的值寫入工作區中的文件。

也許這有幫助。

為當前線程創建一個參數操作。

或者您可以在此處創建一個全局環境變量。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM