hare krshn
hare krshn

Reputation: 386

jenkins groovy logical if conditions validity

I added this below "if" condition in the jenkins groovy script

if ((sign_check == true)  &&  ((name == "abc") ||  (name == "def"))){
println "hello - yes"
}

And even tried using below

if (name == "abc" ||  name == "def"){
 if (sign_check == true) {
  println "hello - yes"
 }
}

When the script is triggered with "sign_check=false" and "name="def", this if condition is supposed not to trigger "hello - yes",yet in my case, it is still happening to trigger "hello - yes".

Please advise what exactly an issue with the if condition.

Upvotes: 0

Views: 16683

Answers (2)

K Akhil
K Akhil

Reputation: 11

In "Declarative syntax", other way is to use "when" condition

pipeline {
  agent any
  parameters
  {
    booleanParam defaultValue: true, description: '', name: 'SIGN_CHECK'
    choice choices: ['abc', 'def'], description: 'What is name?', name: 'NAME'
  }

  stages {
    stage('Hello') {
      when {
        expression {return params.SIGN_CHECK == true}
        anyOf{
            expression { return params.NAME == 'abc'}
            expression { return params.NAME == 'def'}
        }
      }
      steps { println "hello - yes" }
    }
  }
}  

Prints hello - yes

Upvotes: 0

Altaf
Altaf

Reputation: 3076

The issue could be is sign_check variable is not assigned as a boolean. Below are some tests:
Test1 : Gives correct results.
It does not print "hello -yes"

script{
       def sign_check = false
       def name ="abc"
                
      if (name == "abc" ||  name == "def"){
      if (sign_check == true) {
          println "hello - yes"
         }
     }
}

Test1 : Gives correct results.
It does not print "hello -yes"

script{
       def sign_check = false
       def name ="abc"
                
      if (name == "abc" ||  name == "def"){
      if (sign_check == true) {
          println "hello - yes"
         }
     }
}

If you are using paramterised options then you should select variable sign_check as boolean and not string:

pipeline {
    agent any
    parameters
    {
    
        booleanParam(defaultValue: true, description: '', name: 'sign_check')
        string(name: 'name', defaultValue: "abc", description: 'What is name?')
    }
    
    stages {
        stage('Hello') {
            steps {
                script{
                    
                    if (params.name == "abc" ||  params.name == "def"){
                     if (params.sign_check == true) {
                      println "hello - param yes"
                     }
                    }
                    
                }
            }
        }
    }
}

The above gives expected results.

Upvotes: 2

Related Questions