Search code examples
groovyjenkins-groovy

Jenkins groovy dynamically create variables - what is wrong


This is the Jenkins groovy script where .. below is working ..at the stage "validating - line0", the content is correctly returned.

        stage('Read and assign value Groups') {
            steps{
                script {
                def build_properties = readProperties file: "file.txt"
                image_properties.line0 = build_properties.line0
                }
            }
        }

        stage('validating  - line0') {
            steps{
                script {
                     container("${opts.container}") {
                         println("Content: ${image_properties.line0}")

                     }
                    
                }
            }
        }

However, how do we make them dynamic? The below one is not working. What is not working is, in the stage "validating - line0", the content is printing "null". Please advise what is wrong. We wanted to dynamically create the variables and assign the value to other stages.

        stage('Read and assign value Groups') {
            steps{
                script {
                TotalCountline = sh ( script: 'cat file.txt|wc -l', returnStdout: true).trim().toInteger()
                def build_properties = readProperties file: "file.txt"
                for(i=0;i<TotalCountModelGroup;i++) {
                    def var1="image_properties.line$i"
                    def var2="build_properties.line$i"
                   println (var1 + "="+ var2)
                    var1 = var2
                   
                }
                }
            }
        }

        stage('validating  - line0') {
            steps{
                script {
                     container("${opts.container}") {
                         println("line Content: ${image_properties.line0}")

                     }
                    
                }
            }
        }

and file.txt contains


line0=[acme01, acme02, acme03, acme04]
line1=[acme11, acme12, acme13, acme14]
line2=[acme21, acme22, acme23, acme24]
line3=[acme31, acme32, acme33, acme34]

And this is declared at globally, located before "pipeline{}"

def (image_properties, branch) = [ [image_tags:[]], null ]

Solution

  • readProperties returns a java Map (key-value pairs) and you can iterate it with following code:

    def (image_properties, branch) = [ [image_tags:[]], null ]
    def build_properties = readProperties file: "file.txt"
    build_properties.each{ k,v ->
        image_properties[k]=v
    }
    

    or it could be even simpler because image_properties also a Map:

    def (image_properties, branch) = [ [image_tags:[]], null ]
    def build_properties = readProperties file: "file.txt"
    image_properties.putAll(build_properties)
    

    javadoc on Map.putAll(Map)