Properties in a pipeline

31 views
Skip to first unread message

Jochen Wiedmann

unread,
May 17, 2022, 12:52:13 PM5/17/22
to Jenkins Users

Hi,

I've got a build job with a pipeline, like below. (Lots of details omitted, obviously.)

Now, according to the "Pipeline Utility Steps", I understand, that I can use something
like

  def props = readProperties file: 'dir/my.properties', text: 'other=Override'

to read a property file from the workspace. Questions:

  1.) Where in the pipeline script would I place the above statement?
        (Preferrably at a central location, like right at the beginning.)
  2.) How can I use these properties? What I would like to have would be
       something like
           if (props["build.host"]) {
               ssh ${build.host} sh "Some Command"
            } else {
                sh "Some Command"
            }

Thanks,

Jochen



pipeline {
    agent any
    tools {
        maven 'Maven3'
        jdk 'Java8'
    }
    stages {
        stage ('build') {
            steps {
                withMaven(
                ) {
                    script {
                    }
                }
            }
        }
        stage ('collect profiler data') {
            steps {
            }
        }
    }
}

Martin Schmude

unread,
May 20, 2022, 6:06:28 AM5/20/22
to Jenkins Users
This script  

pipeline {
    agent any
    stages {
        stage('play with properties') {
            steps {
                script {
                    def propsText = 'prop1 = val1\nprop2 = val2\nbuild.host=mybuildhost.hosts.myorganization.org'
                    writeFile file: 'myProps.properties', text: propsText
                    def props = readProperties file: 'myProps.properties'
                    echo "${props}"
                    echo props['build.host']
                }
            }
        }
    }
}


works. You can read properties from a properties file into a variable and then access the properties by indexing that variable.  
But you have to place the variable into a script block. The declarative syntax of Jenkins pipelines (https://www.jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline) doesn't allow them anywhere else, in particular not "... right at the beginning.".  
So if you need the properties in several script blocks you have to readProperties them in each of the blocks.  

This is different with the scripted syntax (https://www.jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline) where you can set a variable in an outer block that spans multiple stages, like this:

node {
    def props = ''
    stage('read properties') {
        writeFile file: 'myProps.properties', text: 'prop1 = val1\nprop2 = val2\nbuild.host=mybuildhost.hosts.myorganization.org'
        props = readProperties file: 'myProps.properties'
        echo "${props}"
    }
    stage('access properties') {
        echo props['build.host']
    }
}




Reply all
Reply to author
Forward
0 new messages