Creating a Jenkins Environment Variable Using Groovy

I think this is another simple question, but I could not get any web solutions to work. My project accepts a version number. Each number can be separated by a '.' or '_'. I want a variable that displays only the first two numbers.

I tried writing a groovy script that creates a Jenkins environment variable.
I want to take the first two digits instead of the whole line.

//Get the version parameter def env = System.getenv() def version = env['currentversion'] def m = version =~/\d{1,2}/ env = ['miniVersion':m[0].m[1]] 

I am doing it right, can I create a new environment variable, and is there a better solution for this.

+29
jenkins groovy
May 2 '12 at 12:38
source share
10 answers

Jenkins 1.x

The next groovy fragment should transfer the version (as you have already installed) and save it in the job variables as "miniVersion".

 import hudson.model.* def env = System.getenv() def version = env['currentversion'] def m = version =~/\d{1,2}/ def minVerVal = m[0]+"."+m[1] def pa = new ParametersAction([ new StringParameterValue("miniVersion", minVerVal) ]) // add variable to current job Thread.currentThread().executable.addAction(pa) 

Then the variable will be available from other build steps. eg.

 echo miniVersion=%miniVersion% 

Outputs:

 miniVersion=12.34 

I believe that you will need to use "System groovy Script" (only on the Master node), unlike "Groovy Plugin" - https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin#Groovyplugin- GroovyScriptvsSystemGroovyScript

Jenkins 2.x

I believe the previous behavior ( Jenkins 1.x ) stopped working due to this security recommendation ...

Solution (rephrased from Security Advice)

It is possible to restore the previous behavior by setting the hudson.model.ParametersAction.keepUndefinedParameters system property to true . This is potentially very dangerous and is intended for short-term circumvention only.

 java -Dhudson.model.ParametersAction.keepUndefinedParameters=true -jar jenkins.war 

To allow certain known parameter names to be passed to the assembly, set the hudson.model.ParametersAction.safeParameters system property to a list of safe parameter names, separated by commas.

eg.

 java -Dhudson.model.ParametersAction.safeParameters=miniVersion,FOO,BAR -jar jenkins.war 
+48
Oct 04
source share

You can also define a variable without EnvInject Plugin in your Groovy System Script:

 import hudson.model.* def build = Thread.currentThread().executable def pa = new ParametersAction([ new StringParameterValue("FOO", "BAR") ]) build.addAction(pa) 

You can then access this variable in the next build step, which (for example) is a Windows command command:

 @echo off Setlocal EnableDelayedExpansion echo FOO=!FOO! 

This echo shows you "FOO = BAR".

Hello

+19
Feb 21 '14 at
source share

Jenkins EnvInject Plugin can help you. It allows you to enter environment variables into the build environment.

I know that he has the ability to make scripts, so he can do what you want. I used it only to set simple properties (for example, "LOG_PATH = $ {WORKSPACE} \ logs").

+9
May 02 '12 at 14:00
source share

As other answers, state setting new ParametersAction is a way to enter one or more environment variables, but when the task is already parameterized, adding a new action will not take effect. Instead, you will see two links to assembly parameters pointing to the same set of parameters, and the one you want to add will be null .

Here is a fragment updating the list of parameters in both cases (parameterized and non-parameterized task):

 import hudson.model.* def build = Thread.currentThread().executable def env = System.getenv() def version = env['currentversion'] def m = version =~/\d{1,2}/ def minVerVal = m[0]+"."+m[1] def newParams = null def pl = new ArrayList<StringParameterValue>() pl.add(new StringParameterValue('miniVersion', miniVerVal)) def oldParams = build.getAction(ParametersAction.class) if(oldParams != null) { newParams = oldParams.createUpdated(pl) build.actions.remove(oldParams) } else { newParams = new ParametersAction(pl) } build.addAction(newParams) 
+9
Sep 11 '14 at 20:37
source share

For me, the following worked in Jenkins 2 (2.73.3)

replace

 def pa = new ParametersAction([new StringParameterValue("FOO", foo)]) build.addAction(pa) 

from

 def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"]) build.addAction(pa) 

ParametersAction seems to have a second constructor that allows you to pass "AdditionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java

+9
Jan 22 '18 at 9:01
source share

After searching a bit, the best solution, in my opinion, uses hudson.model.EnvironmentContributingAction.

 import hudson.model.EnvironmentContributingAction import hudson.model.AbstractBuild import hudson.EnvVars class BuildVariableInjector { def build def out def BuildVariableInjector(build, out) { this.build = build this.out = out } def addBuildEnvironmentVariable(key, value) { def action = new VariableInjectionAction(key, value) build.addAction(action) //Must call this for action to be added build.getEnvironment() } class VariableInjectionAction implements EnvironmentContributingAction { private String key private String value public VariableInjectionAction(String key, String value) { this.key = key this.value = value } public void buildEnvVars(AbstractBuild build, EnvVars envVars) { if (envVars != null && key != null && value != null) { envVars.put(key, value); } } public String getDisplayName() { return "VariableInjectionAction"; } public String getIconFileName() { return null; } public String getUrlName() { return null; } } } 

I use this class in a groovy script system (using the groovy plugin) in a job.

 import hudson.model.* import java.io.File; import jenkins.model.Jenkins; def jenkinsRootDir = build.getEnvVars()["JENKINS_HOME"]; def parent = getClass().getClassLoader() def loader = new GroovyClassLoader(parent) def buildVariableInjector = loader.parseClass(new File(jenkinsRootDir + "/userContent/GroovyScripts/BuildVariableInjector.groovy")).newInstance(build, getBinding().out) def projectBranchDependencies = [] //Some logic to set projectBranchDependencies variable buildVariableInjector.addBuildEnvironmentVariable("projectBranchDependencies", projectBranchDependencies.join(",")); 

Then you can access the projectBranchDependencies variable at any other point in your assembly, in my case, from an ANT script.

Note. I borrowed / modified ideas for parts of this implementation from a blog post, but during this post I could not find the original source to give credit.

+7
Apr 7 '16 at 13:18
source share

Just the same problem. You need to dynamically run parameterized downstream jobs based on the results of some groovy scripts.

Unfortunately, it is not possible to run System groovy scripts on our Jenkins. So I had to make a small workaround:

  • Run a groovy script that creates a properties file that sets the given environment variable

     def props = new File("properties.text") if (props.text == 'foo=bar') { props.text = 'foo=baz' } else { props.text = 'foo=bar' } 
  • Use the env plugin to inject the variable written into this script

     Inject environment variable Property file path: properties.text 

After that, I was able to use the variable 'foo' as a parameter for the parameterized trigger plugin. Some kind of workaround. But it works!

+4
09 Sep '15 at 16:48
source share

My environment was a previous snap-in such as Jenkins, and worked with batch files (I know, I'm old). Thus, these batch files (and their supporting files) use environment variables. This was my piece of groovy script that introduces environment variables. The names and parameters used are fictitious.

 // The process/batch which uses environment variables def buildLabel = "SomeVersionNr" def script = "startBuild.bat" def processBuilder = new ProcessBuilder(script, buildLabel) //Inject our environment variables Map<String, String> env = processBuilder.environment() env.put("ProjectRoot", "someLocation") env.put("SomeVar", "Some") Process p = processBuilder.start() p.waitFor() 

Of course, if you install Jenkins from scratch, you will probably do it differently and share the variables differently or pass parameters, but that may come in handy.

+1
Aug 4 '17 at 17:31 on
source share

I am stuck. So I have to write a great script to set the environment variable for EDAConnect for the perception software ... It seems I can not get all of the above to work correctly.

Anyone have any experience or tips on the next?

 9073039 [ModalContext] ERROR com.perception.scripting.engines.BSFEngine - Exception : 

java.security.PrivilegedActionException: org.apache.bsf.BSFException: exception from Groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: failed to run, script: 174: cannot resolve the ParametersAction class @ row 174, column 10.Script: 175 :: cannot resolve the StringParameterValue class @ row 175, column 1.Script: 176: cannot resolve the StringParameterValue class @ row 176, column 1. 3 errors

 at java.security.AccessController.doPrivileged(Native Method) at org.apache.bsf.BSFManager.exec(BSFManager.java:491) at com.perception.scripting.engines.BSFEngine.execute(BSFEngine.java:89) at com.perception.scripting.engines.BSFEngine.execute(BSFEngine.java:233) at com.perception.scripting.core.ScriptingWorker.runEventScript(ScriptingWorker.java:114) at com.perception.scripting.core.ScriptingWorker.fireEvent(ScriptingWorker.java:350) at com.perception.scripting.core.ScriptingWorker.fireEvent(ScriptingWorker.java:309) at com.perception.edac.data.model.scripting.ScriptingController.fireEvent(ScriptingController.java:199) at com.perception.edaconnect.modules.ds.DSController.fireLoadDesignStructureEvent(DSController.java:614) at com.perception.edaconnect.modules.wizards.checkin.CheckinMainPage$11$1.run(CheckinMainPage.java:415) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) 

Raised: org.apache.bsf.BSFException: exception from Groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: failed to run, script: 174: cannot resolve class ParametersAction @ row 174, column 10.Script: 175: cannot resolve class StringParameterValue @ row 175, column 1.Script: 176: cannot resolve the class StringParameterValue @ row 176, column 1. 3 errors

 at org.codehaus.groovy.bsf.GroovyEngine.exec(GroovyEngine.java:110) at org.apache.bsf.BSFManager$6.run(BSFManager.java:493) ... 11 more 

9073040 [ModalContext] ERROR com.perception.scripting.core.ScriptingWorker - Script com.perception.scripting.core.ScriptingException failed: org.apache.bsf.BSFException: exception from Groovy: org.codehaus.groovy.control.ation. EmpleCr. launch failed, script: 174: cannot resolve the class ParametersAction @ row 174, column 10.Script: 175: cannot resolve the class StringParameterValue @ row 175, column 1.Script: 176: cannot resolve the class StringParameterValue @ row 176, column 1 3 errors

 at com.perception.scripting.engines.BSFEngine.execute(BSFEngine.java:94) at com.perception.scripting.engines.BSFEngine.execute(BSFEngine.java:233) at com.perception.scripting.core.ScriptingWorker.runEventScript(ScriptingWorker.java:114) at com.perception.scripting.core.ScriptingWorker.fireEvent(ScriptingWorker.java:350) at com.perception.scripting.core.ScriptingWorker.fireEvent(ScriptingWorker.java:309) at com.perception.edac.data.model.scripting.ScriptingController.fireEvent(ScriptingController.java:199) at com.perception.edaconnect.modules.ds.DSController.fireLoadDesignStructureEvent(DSController.java:614) at com.perception.edaconnect.modules.wizards.checkin.CheckinMainPage$11$1.run(CheckinMainPage.java:415) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) 

Raised: org.apache.bsf.BSFException: exception from Groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: failed to run, script: 174: cannot resolve class ParametersAction @ row 174, column 10.Script: 175: cannot resolve class StringParameterValue @ row 175, column 1.Script: 176: cannot resolve the class StringParameterValue @ row 176, column 1. 3 errors

 at org.codehaus.groovy.bsf.GroovyEngine.exec(GroovyEngine.java:110) at org.apache.bsf.BSFManager$6.run(BSFManager.java:493) at java.security.AccessController.doPrivileged(Native Method) at org.apache.bsf.BSFManager.exec(BSFManager.java:491) at com.perception.scripting.engines.BSFEngine.execute(BSFEngine.java:89) ... 8 more 
0
Jun 06 '19 at 5:27
source share

For my part, this only worked by replacing the existing parameter.

 def artifactNameParam = new StringParameterValue('CopyProjectArtifactName', 'bla bla bla') build.replaceAction(new ParametersAction(artifactNameParam)) 

In addition, this script must be run with the Groovy system .

The clockwork must be set manually on this system and the Groovy bin deer must be added to the path. Additionally, I had to add jenkins-core.jar to the lib folder.

Then it was possible to change the parameter in the groovy script and get the changed value in the batch script after continuing.

0
Jun 26 '19 at 13:21
source share



All Articles