简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM