Search code examples
javajenkinsgroovyjenkins-groovy

Iterate over String


So, I have this problem:

    #!/usr/bin/env groovy
    
    package com.fsfs.fdfs.fsf.utils
    
    class GlobalVars {
        // TEST-DEV
        static String MY_URL1 = "https://myurl.com"
        static String MY_URL2 = "https://:6443"
        static String MYURLS_TEST = "${MY_URL1} ${MY_URL2}"

}

So I want to iterate over my URLS depending on the environment.

For example: in this ENV is TEST, but could be DEV, PROD and so on

 for( Name in GlobalVars."MYURLS_${ENV}".split(/\s+/)) {

    }

I'm not sure how to achieve this. Basically, I want to iterate over a variable with a dynamic name. The variable contains at least 2 strings


Solution

  • You could do something like this...

    class GlobalVars {
            // TEST-DEV
            static String MY_URL1 = "https://myurl.com"
            static String MY_URL2 = "https://:6443"
            static String MYURLS_TEST = "${MY_URL1} ${MY_URL2}"
    }
    
    String ENV = 'TEST'
    for( name in GlobalVars."MYURLS_${ENV}".split(/\s+/)) {
        println name
    }