Search code examples
jenkinsjenkins-workflow

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?


Solution

  • 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"
    }