Ziv M
Ziv M

Reputation: 417

Jenkins file, check if Globals variable exists

I have jenkinsfile with defined Globals varible for timeout

class Globals {
    static String TEST_TIMEOUT = ""
}

I am using functions from shared library I am using the global variable to set a timeout for function. Since the shared library used by other projects that doesn't define the Globals variable I defined environment variable in the function file to be used as default value for time out.

env.TESTS_TIME_OUT="10080"

Then in function I want to check if Globals variable exists, I want to use the value as time out, if not the to use the default value.

if(Globals.TEST_TIMEOUT){
   env.TESTS_TIME_OUT= "${Globals.TEST_TIMEOUT}"   
}
timeout(time: "${env.TESTS_TIME_OUT}", unit: 'MINUTES') {
.
.
.
}

I`ve done it before with success on env parameters, but this time I am getting an error

No such field found: field java.lang.Class TEST_TIMEOUT 

Any ideas how to solve this ? Or Any other way to check if Globals variable exists ?

Thank you

Upvotes: 2

Views: 4424

Answers (1)

zett42
zett42

Reputation: 27756

You can catch groovy.lang.MissingPropertyException which will be thrown if either Globals or Globals.TEST_TIMEOUT does not exist:

try {
    env.TESTS_TIME_OUT = Globals.TEST_TIMEOUT
}
catch( groovy.lang.MissingPropertyException e ) {
    env.TESTS_TIME_OUT = "10080"
}

You could even move this pattern into a generic function...

def getPropOrDefault( Closure c, def defaultVal ) {
    try {
        return c()
    }
    catch( groovy.lang.MissingPropertyException e ) {
        return defaultVal
    }
}

... which could be called like this:

env.TESTS_TIME_OUT = getPropOrDefault({ Globals.TEST_TIMEOUT }, '10080')

This could be useful if there are many different globals that you want to treat similar. Safes you from writing many try/catch blocks.

The closure is required to make sure that the expression Globals.TEST_TIMEOUT will be evaluated inside of the try/catch block of getPropOrDefault instead of before the function call.

Upvotes: 5

Related Questions