Search code examples
jenkinscontinuous-integrationjenkins-pipelinejenkins-plugins

Jenkins Pipeline best way to use choice parameter for checking conditions


Pipeline executes two jobs : Job X and Job Y. The Pipeline has a choice parameter which is required by Job Y. Choice parameter options: A,B and C.

Job Y has 3 conditions :

if Choice==A then do task 1

else if Choice==B then do task 2

else do task 3

Getting stuck at declaring choice conditions at STAGE of Job Y.

p.s. tried Active Choice parameter, can't work through it.

Can anybody help out with the logic for this problem?


Solution

  • I am assuming that Job Y is called from your pipeline as a downstream job. Thus somewhere, (probably the end of your pipeline) you will have:

    build job: 'CloudbeeFolder1/Path/To/JobY', propagate: false, wait: false, parameters: [[$class: 'StringParameterValue', name: 'MY_PARAM', value: "${env.SOME_VALUE}"]]

    Then in JobY on the "other side" you have:

    environment {
        PARAM_FROM_PIPELINE = "${params.MY_PARAM}"
    }
    

    This gets the value of your parameter into an environment variable in JobY.

    Depending on what the tasks are you could perform them in a batch (or sh) file by passing PARAM_FROM_PIPELINE like so:

    stages {
        stage("Do Tasks") {
            steps {
                bat "mybatchfile.bat ${env.PARAM_FROM_PIPELINE}"
            }
        }
    }
    

    Finally in mybatchfile.bat you can read the value of ${env.PARAM_FROM_PIPELINE} like so:

    @ECHO OFF
    
    SET PARAM_VAL=%1
    ECHO PARAM VALUE IS: %PARAM_VAL%
    
    IF %PARAM_VAL% = "A" (
      REM DO TASK1
    ) ELSE (
        IF %PARAM_VAL% = "B" (
            REM DO TASK2
        ) ELSE (
            REM DO TASK3
        )
    )
    

    If you don't want to encapsulate the if-else logic in a batch file you can use a script {...} block in your Jenkinsfile to use scripted pipeline.