Blog

Use Choice Parameter in Jenkins declarative pipeline?

Jenkins

Use Choice Parameter in Jenkins declarative pipeline?

In Jenkins declarative pipelines, the choice parameter is used to create a parameterized build that allows users to select a value from a predefined list of choices. This can be useful for customizing the behavior of your pipeline job based on user input.

Lets see how you can use the choice parameter in a declarative pipeline:

Define the Parameter in Jenkins:

Before you set up your pipeline, you need to define the parameter in your Jenkins job configuration.

1. Go to your Jenkins dashboard.

2. Find and select the job for which you want to add the choice parameter.

3. Click on “Configure” to edit the job.

4. Scroll down to the “Build” section and click on the “Add Parameter” dropdown.

5. Choose “Choice Parameter” from the list.

6. Enter a name for the parameter, for example, operating-system.

7. Configure the choices and other settings as needed, then save your job configuration.

Use the Choice Parameter in Declarative Pipeline:

Once you’ve configured the choice parameter in your Jenkins job, you can use it in your declarative pipeline script.

pipeline {
    agent any
     
    parameters {
        choice(name: 'operating-system', choices: 'Linux\nCentOS\nAmazon-Linux', description: 'Select a operating-system')
    }
 
    stages {
        stage('build') {
            steps {
                script {
                    echo "Selected operating-system: ${params.operating-system}"
                }
            }
        }
    }
}

In this example, the choice parameter named operating-system is defined with three choices: Linux, CentOS, and Amazon-Linux. The parameter is accessed using the params object in the pipeline script.

Run the Pipeline:

When you trigger the Jenkins job, you will be presented with a dropdown list of choices for the operating-system parameter. Select one of the options and start the build. The selected value will be available in your pipeline steps as params.operating-system.

Spread the love

Leave your thought here

Your email address will not be published. Required fields are marked *