Old question, and there are maybe some better solutions now, but I didn't find them, so posting this anyway in case it helps.
@link69 answer is really good, and led me to something maybe a bit more advanced,
which allows choosing whereas a user provided value is stored or not as the default value.
On my side, there are parameters that I would like to be "one shot", eg "debug build", while I would like to be able to set some persistent parameters from the UI (eg git branch to be used).
The main drawback is that the pipeline doesn't know if a parameter has been modified from the project "configure" page or in "build with parameters", and saves the value as "default" in both cases.
I also don't like to repeat the parameter name twice for each parameter in the parameters
block.
// Update parameters[paramName] with defaultValue if paramName key is not present,
// Return the default value
def <T> T updateMapReturnDefault(Map parameters, String paramName, T defaultValue)
{
if (!parameters.containsKey(paramName))
parameters[paramName] = defaultValue
return defaultValue
}
// Update parameters[paramName] with defaultValue if paramName key is not present,
// Return the value read from the map if present, the default value otherwise
def <T> T updateMapReturnValue(Map parameters, String paramName, T defaultValue)
{
if (!parameters.containsKey(paramName))
parameters[paramName] = defaultValue
return parameters[paramName]
}
def call(Map config) {
node {
// Copy params map to allow modifying it
userParams = new HashMap(params)
properties([
parameters([
// Value will be stored as default on each build
string(name: "GIT_BRANCH", defaultValue: updateMapReturnValue(userParams, "GIT_BRANCH", "main")),
// Value will be reset on each build
booleanParam(name: "DEBUG_BUILD", defaultValue: updateMapReturnDefault(userParams, "DEBUG_BUILD", false)),
// Set JUST_UPDATE_PARAMETERS to true to update the parameters list and exit
// True by default so that the first build just updates the parameters
booleanParam(name: "JUST_UPDATE_PARAMETERS", defaultValue: updateMapReturnValue(userParams, "JUST_UPDATE_PARAMETERS", true)),
])
])
if (userParams.JUST_UPDATE_PARAMETERS) {
stage("Update pipeline parameters") {
println("JUST_UPDATE_PARAMETERS is set, not building")
currentBuild.displayName = "parameters update"
return
}
}
stage("build") {
println("Build started, branch ${userParams.GIT_BRANCH}, debug_build: ${userParams.DEBUG_BUILD}")
}
}
}