Home > Blockchain >  Change job parameter value in jenkins using groovy
Change job parameter value in jenkins using groovy

Time:05-30

I have a default values for each parameter in Jenkins pipeline, now I just want to replace one of the parameter present in it, how to do it using groovy?

I have searched exhaustedly but nothing seems to work :(

I tried the below code, it works without any errors but the job is getting scheduled is not having the updated parameter(env_name) value, It is having the default value

def getCause(){
return new CauseAction(new hudson.model.Cause.UserIdCause('admin-user'))
}

def job = Jenkins.instance.getItemByFullName('JobName');
if(job && job.isBuildable()){
   def newParameter = new StringParameterValue('env_name', 'dev') 
   job.replaceAction(new ParametersAction(newParameter))
   def buildResult = job.scheduleBuild2(0, getCause())
}

CodePudding user response:

This can be solved differently, explored some ways and found the way to modify an existing build property in jenkins

def formParam(job){
    ParametersDefinitionProperty params = job.getProperty(ParametersDefinitionProperty.class);
    List<ParameterValue> newParams = new ArrayList<>();
    params.getParameterDefinitions().each{param -> newParams.add(param.getDefaultParameterValue())};
    newParams.removeIf{param -> param.getName().contains("env_name")};
    newParams.add(new StringParameterValue("env_name","dev",""))
    return newParams;
}

def main(){
    def job = Jenkins.instance.getItemByFullName('JobName');
    def paramlist = formParam(job);
    def future = job.scheduleBuild2(0, getCause(), new ParametersAction(paramlist));
}

The params variable would have all the build properties of the job specified, I'm creating a newParams list and adding the default values to it. After adding, I'm removing the one I'm going to replace, and then adding a new value to same key. This is a working solution, it even does not modify the job config of the jenkins job.

  • Related