Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect in Jenkins Workflow if parameterized build parameter exists or not?

What is the best way that I can detect if a parameter in a parameterized build exists or not? The closest solution I found was to do this in groovy:

node {
   groovy.lang.Binding myBinding = getBinding()
   boolean mybool = myBinding.hasVariable("STRING_PARAM1")
   echo mybool.toString()
   if (mybool) {
       echo STRING_PARAM1
       echo getProperty("STRING_PARAM1")
   } else {
       echo "STRING_PARAM1 is not defined"
   }

   mybool = myBinding.hasVariable("DID_NOT_DEFINE_THIS")
   if (mybool) {
       echo DID_NOT_DEFINE_THIS
       echo getProperty("DID_NOT_DEFINE_THIS")
   } else {
       echo "DID_NOT_DEFINE_THIS is not defined"
   }
}

Is using getBinding() the proper API to do this, or is there a better way?

like image 572
Craig Rodrigues Avatar asked Dec 15 '22 09:12

Craig Rodrigues


2 Answers

You can use try-catch to check for the existence of a parameter:

try {
    echo TEST1
    echo 'TEST1 is defined'
} catch (err) {
    echo 'TEST1 is not defined'
}
like image 67
amuniz Avatar answered May 16 '23 05:05

amuniz


When you are using Pipelines then you have access to the object: params whichs is a Java map, then you can use: containsKey method, i.e:

if(params.containsKey("STRING_PARAM1")) {
   echo "STRING_PARAM1 exists as parameter with value ${STRING_PARAM1}"
} else {
   echo "STRING_PARAM1 is not defined"
}
like image 37
Daniel Hernández Avatar answered May 16 '23 04:05

Daniel Hernández