themaniac27 themaniac27 - 1 year ago 759
Groovy Question

Creating a Jenkins environment variable using Groovy

I think this is another simple question but I couldn't get any of the web solutions to work. My project takes in a version number. Each number can be separated by a '.' or a '_'. I want a variable that only displays 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 entire string.

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

Am I doing this correctly, can I even create a new environment variable, and is there a better solution to this.

Answer Source

Jenkins 1.x

The following groovy snippet should pass the version (as you've already supplied), and store it in the job's 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

The variable will then be accessible from other build steps. e.g.

echo miniVersion=%miniVersion%



I believe you'll need to use the "System Groovy Script" (on the Master node only) as opposed to the "Groovy Plugin" -

Jenkins 2.x

I believe the previous (Jenkins 1.x) behaviour stopped working because of this Security Advisory...

Solution (paraphrased from the Security Advisory)

It's possible to restore the previous behaviour by setting the system property hudson.model.ParametersAction.keepUndefinedParameters to true. This is potentially very unsafe and intended as a short-term workaround only.

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

To allow specific, known safe parameter names to be passed to builds, set the system property hudson.model.ParametersAction.safeParameters to a comma-separated list of safe parameter names.


java -Dhudson.model.ParametersAction.safeParameters=miniVersion,FOO,BAR -jar jenkins.war
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download