How can I reference my constant within a Jenkins Parameter?

586 Views Asked by At

I have the following code in a Pipelineconstant.groovy file:

public static final list ACTION_CHOICES = [
    N_A,
    FULL_BLUE_GREEN,
    STAGE,
    FLIP, 
    CLEANUP
]

and this PARAMETERS in Jenkins multi-Rapper-file:

parameters {
    string (name: 'ChangeTicket', defaultValue: '000000', description : 'Prod change ticket otherwise 000000')
    choice (name: 'AssetAreaName', choices: ['fpukviewwholeof', 'fpukdocrhs', 'fpuklegstatus', 'fpukbooksandjournals', 'fpukleglinks', 'fpukcasesoverview'], description: 'Select the AssetAreaName.')
    /* groovylint-disable-next-line DuplicateStringLiteral */
    choice (name: 'AssetGroup', choices: ['pdc1c', 'pdc2c'])
}

I would like to ref ACTION_CHOICES in the parameter as this:

choice (name: 'Action', choices: constants.ACTION_CHOICES, description: 'Multi Version deployment actions')

but it doesn't work for me.

I tried to do this:

choice (name: 'Action', choices: constants.ACTION_CHOICES, description: 'Multi Version deployment actions')

but it doesn't work for me.

1

There are 1 best solutions below

2
On

You're almost there! Jenkinsfile(s) can be extended with variables / constants defined (directly in your file or (better I'd say) from a Jenkins shared library (this scenario).

The parameter syntax within you pipeline was fine as well as the idea of lists of constants, but what was missing: a proper interlink of those parts together - proper library import. See example below (the names below in the example are not carved in stone and can be of course changed but watch out - Jenkins is quite sensitive about filenames, paths, ... (especially in shared libraries]):

Pipelineconstant.groovy should be placed in src/org/pipelines of your Jenkins shared library.

Pipelineconstant.groovy

package org.pipelines

class Pipelineconstant {
   public static final List<String> ACTION_CHOICES = ["N_A", "FULL_BLUE_GREEN", "STAGE", "FLIP", "CLEANUP"]
}

and then you can reference this list of constants within your Jenkinsfile pipeline.

Jenkinsfile

@Library('jsl-constants') _
import org.pipelines.Pipelineconstant


 pipeline {
    agent any   

    parameters {
        choice (name: 'Action', choices: Pipelineconstant.ACTION_CHOICES , description: 'Multi Version deployment actions')
    }

    // rest of your pipeline code

}

The first two lines of the pipeline are important - the first loads the JSL itself! Therefore the second line of that import can be used (otherwise Jenkins would not know where find that Pipelineconstant.groovy file.


B) Without Jenkins shared library (files in one repo):

I've found this topic discussed and solved for scripted pipeline here: Load jenkins parameters from external groovy file