Search code examples
jenkinsconfigurationcontinuous-integrationjenkins-pipelinejenkins-plugins

Jenkins change choice parameter value automatically based on the week day


In my jenkins job, I have a choice parameter containing 4 values (val1, val2, val3, val4).

Is it possible to set dynamically the choice parameter value based on a recurrent temporal event?

More precisely, I would like to change dynamically this value every Monday of the year.

For example:

Monday March 16 => it takes val1 
Monday March 23 => it takes val2 
Monday March 30 => it takes val3 
Monday April 6  => it takes val4 
Monday April 13 => it takes val1

and so on.


Solution

  • So, your question basically boils down to two:

    1. How can I programmatically determine which value to select, based on current date?
    2. Having that figured out, how can I cause that value to be the default in the choice parameter of the pipeline?

    Considering you're doing fine by yourself with #1 (may include getting the week number and taking the remainder of that divided by 4), let's tackle the second question.

    To modify the choices parameter based on the result of some arbitrary Groovy script, you may want to run a scripted pipeline before your declarative one, something like this:

    def use_as_default = getValToUseAsDefault() // val1 on March 16, etc.
    
    def list_of_vals = []
    
    list_of_vals += use_as_default // first in the list will get to be selected
    
    if (! ("val1" in list_of_vals) ) { list_of_vals += "val1"}
    if (! ("val2" in list_of_vals) ) { list_of_vals += "val2"}
    if (! ("val3" in list_of_vals) ) { list_of_vals += "val3"}
    if (! ("val4" in list_of_vals) ) { list_of_vals += "val4"}
    
    list_of_vals = Arrays.asList(list_of_vals)
    
    pipeline
    {
        agent any
    
        parameters
        {
            choice(name: 'VALS', choices: list_of_vals, description: 'Choose value')
        }
    ...
    }
    
    def getValToUseAsDefault() {
       // left as exercise to OP
       return "val1"
    }