简体   繁体   中英

Set environment variables from Groovy script in Jenkins

I have got a FreeStyle project in Jenkins. One part of the build is an "Execute Groovy script" build step (important: not an 'Execute System Groovy script' step - that would not work).

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?

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. 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. 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.

Maybe this helps.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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