Home > Mobile >  Jenkins Declarative Piplines- Script is unable to pickup parameter as varible
Jenkins Declarative Piplines- Script is unable to pickup parameter as varible

Time:01-12

I am New to Jenkins. Trying to create one basic Pipeline which is using choicebased parameters. Following is my script.

Code ----

  pipeline{
     agent {
        label 'agent'
           } 
     parameters {
        choice choices: ['John', 'Stacy'], description: 'Choose one', name: 'Person'
         }
     stages {
        stage('Print') {
            steps {
               echo "Hello ${params.Person}"
               sh """if (${params.Person} = "John")
                     then
                       echo "Person is male."
                     else
                        echo "Person is female."
                     fi"""
                }
                    }
     } 
  }

Now my build complete successfully regardless of whatever option I choose. It always display result "Person is female.

Following is result of one of my build.

Started by user ****
[Pipeline] Start of Pipeline
[Pipeline] node
Running on agent in 
 /home/temp/jenkins_agent/workspace/ChoiceBased PL
 [Pipeline] {
 [Pipeline] stage
 [Pipeline] { (Print)
 [Pipeline] echo
 Hello John
 [Pipeline] sh
   John = John
  /home/temp/jenkins_agent/workspace/ChoiceBased PL@tmp/durable- 
 b7e98c46/script.sh: 1: John: not found
   echo Person is female.
 Person is female.
 [Pipeline] }
 [Pipeline] // stage
 [Pipeline] }
 [Pipeline] // node
 [Pipeline] End of Pipeline

Finished: Success

Please suggest what I am missing ?

CodePudding user response:

I would change this just to be in Groovy rather than doing the compare in sh

    stage('Print') {
        steps {
           echo "Hello ${params.Person}"
           script {
               if (params.Person == "John") {
                   echo "Person is male."
               } else {
                   echo "Person is female."
               }
            }
        }
    }

Then when you choose Stacey you will get

[Pipeline] echo
Hello Stacy
[Pipeline] script
[Pipeline] {
[Pipeline] echo
Person is female.
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
  •  Tags:  
  • Related