I'm trying the change a parameter value in a Jenkins pipeline. Here's my latest script code:
// Replace spaces in PROJECT_NAME parameter with dashes
script {
def build = currentBuild.build()
def parms = build.getActions(ParametersAction).get(0)
for (ParameterValue parm : parms.getParameters()) {
StringBuilder msg = new StringBuilder()
msg.append(parm.getName())
msg.append(": ")
if (parm.getValue() == null) {
msg.append("<null>")
} else {
msg.append(String.valueOf(parm.getValue()))
}
print(msg)
}
def projectNameWithoutSpaces = new StringParameterValue("PROJECT_NAME", "${params.PROJECT_NAME}".replaceAll(" ", "-"))
build.replaceAction(parms.createUpdated(Arrays.asList(projectNameWithoutSpaces)))
}
I'm finding that parms contains the default parameter values rather than the values specified in the pipeline build. This, in turn, is causing build.replaceAction(parms.createUpdated(Arrays.asList(projectNameWithoutSpaces))) to replace all parameter values except for the PROJECT_NAME value with the parameter's default value.
Why does parms contain default parameter values rather than the values specified in the pipeline build? How do I get the specified parameter values so that I can correctly change the value of the PROJECT_NAME parameter?
This was a user error on my part; currentBuild.build().getActions(ParametersAction).get(0) does return the correct parameter values. It turns out that one of my earlier failed attempts had set all of my pipeline's parameter values, except for the PROJECT_NAME parameter value, to their default values.
One side effect of using build.replaceAction() is that it actually changes the pipeline build's PROJECT_NAME parameter value in the Jenkins web client. So when I go to do a rebuild, the PROJECT_NAME parameter has the update value (spaces replaced with dashes), which is really not what I want.
Also, early on I tried the simpler solution of simply setting params.PROJECT_NAME to the new value:
// Replace spaces in PROJECT_NAME parameter with dashes
script {
params.PROJECT_NAME = "${params.PROJECT_NAME}".replaceAll(" ", "-")
}
However, this failed with an java.lang.UnsupportedOperationException as the params object is backed by java.util.Collections$UnmodifiableMap.
I wasn't aware that the pipeline parameters values are also available via the env object (thanks to zett42 for pointing this out). So I tried setting env.PROJECT_NAME:
// Replace spaces in PROJECT_NAME parameter with dashes
script {
env.PROJECT_NAME = "${env.PROJECT_NAME}".replaceAll(" ", "-")
}
This worked just fine without changing the pipeline build's PROJECT_NAME parameter value in the Jenkins web client.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With