Jenkins - Pass Parameters within Build using Groovy

Posted:   August 14, 2018

Edited:   August 10, 2018

Status:   Completed

Tags :   Python

Categories :   Python

Were equations, pictures or diagrams not properly rendered, please refresh the page. If the problem persists, you can contact me.

Background

We have a job which has two build steps:

  • a groovy step to generate runtime build parameters, which will be used for following steps
  • a windows batch build step to consume the runtime build parameters generated by the groovy step

This works well in Jenkins 1.0, but after migrated to Jenkins 2.0, it retired.

Analysis

After a google search, it turned out that Jenkins 2.0 has injected a new security advisory, where previous allowed arbitrary parameters are accepted as environment variables, but that is not safe. Now Jenkins forces to use build parameters. But there are always exceptions, for known safe parameters are still allowed in below way:

java -Dhudson.model.ParametersAction.safeParameters=FOO,BAR_BAZ,qux -jar jenkins.war

correspondingly if user is using groovy script to add new ParamtersAction, there is also a corresponding constructor to use.

Solution

So in Jenkins 1.0, we have:

import hudson.model.*
  
def build = Thread.currentThread()?.executable
def param = new ParametersAction([new StringParameterValue("NEW_PARAM",lang)])
build.addAction(param)
return param

Now in Jenkins 2.0:

import hudson.model.*
  
def build = Thread.currentThread()?.executable
def param = new ParametersAction([new StringParameterValue("NEW_PARAM",lang)], ["NEW_PARAM"])
build.addAction(param)
return param

very small change huh, but it avoids redesign the jobs.

To use this new-added parameter, in later build steps e.g. windows batch command step:

echo %NEW_PARAM%

Reference

https://stackoverflow.com/questions/10413936/creating-a-jenkins-environment-variable-using-groovy

https://itisatechiesworld.wordpress.com/jenkins-related-articles/jenkins-configuration/jenkins-environment-variables/

Comments


Be the first one to comment on this page!
You can use extended GitHub flavored markdown in your comment. Commenting FAQs & Guidelines