Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkinsfile one type of parameter instead of two type, convert choice into string or string into choice


I'm using two parameters one is choice (ID) and other one string (NID) but values are same. Requirement is to use only parameter either choice or string. Is it possible to convert choice parameter into string or string to choice parameter? so that i can use one parameter and one deploy function.

def deploy1(env) {
step([$class: 'UCDeployPublisher',
siteName: siteName,
deploy: [
$class: 'com.urbancode.jenkins.plugins.ucdeploy.DeployHelper$DeployBlock',
deployApp: appName,
deployEnv: 'DEV',
deployVersions: "${compName}:${version}",
deployProc: simpleDeploy,
deployOnlyChanged: false,
deployReqProps: "ID=${params.ID}" ===> string paramater
]])

def deploy2(env) {
step([$class: 'UCDeployPublisher',
siteName: siteName,
deploy: [
$class: 'com.urbancode.jenkins.plugins.ucdeploy.DeployHelper$DeployBlock',
deployApp: appName,
deployEnv: 'DEV',
deployVersions: "${compName}:${version}",
deployProc: simpleDeploy,
deployOnlyChanged: false,
deployReqProps: "ID=${params.NID}"  ===> Needs choice paramater
]])

parameters {
choice(
name: 'ID',
choices: [ '8922', '9292', '3220' ]
 )

string(
name: 'NID',
defaultvalue: '8922,9292,3220'  
)

stage (DEV') {
steps {
    script {
     if (params.ENVIRONMENT == "dev"){
         deploy1('devl') ===> this will call my deploy function
      }
     }
    }
  }

Solution

  • Yes you can convert the string parameter to an array by just using split:
    Below is an example :

    // Define list which would contain all servers in an array
    def ID= []
    pipeline {
        agent none
         parameters
        {
            // Adding below as example string which is passed from paramters . this can be changed based on your need
            // Example: Pass NID list as , separated string in your project. This can be changed 
            string(name: 'NID', defaultValue:'8922,9292,3220', description: 'Enter , separated NID values in your project e.g. 8922,9292,3220')
        }
        stages {
            stage('DEV') {
                agent any
                steps {
                    
                    script
                    {
                        // Update ID list
                        ID= params.NID.split(",")
                        // You can loop thorugh the ID list
                        for (myid in ID)
                        {
                            println ("ID is : ${myid}") 
                        }
                    }
                }
            }
        }
    }