groovyjenkins-pipeline

How do I use groovy variables set from a properties file?


I have this simple properties file

a=1
b=2

And the following groovy code

    stage('Load Properties') {
        steps{
            script{
                props = readProperties file:"application.properties"
                keys= props.keySet()
                for(key in keys) {
                    value = props["${key}"]
                    env."${key}" = "${value}"
                }
            }
        }
    }
    stage('Use Properties') {
        steps{
                script {
                    println "a: ${a}"
                    sh '''
                        echo "a: ${a}"  
                    '''
                }
            }
        }
    }

But the output makes no sense:

[Pipeline] script
[Pipeline] {
[Pipeline] echo
a: 1
[Pipeline] sh
+ echo 'a: '
a: 

echo "a: ${env.a}" just returns "${env.a}: bad substitution"


Solution

  • There are various syntax, scope, and usage issues here which we can fix:

    stage('Properties') {
      steps {
        script {
          Map props = readProperties(file: 'application.properties')
          for(key in props.keySet()) {
            env[key] = props[key]
          }
          // note this resolve the properties variable value since it is Groovy interpreted ...
          println "a: ${a}"
          // ... and this resolve the environment variable value since it is shell interpreted
          sh(
            label: 'Print env var values',
            script: '''
              echo "a: ${a}"
              echo "b: ${b}"
            '''
          )
        }
      }
    }