How to read property from config file inside Jenkins pipeline using Config File Provider Plugin

14,403

Solution 1

With the help of the other answers and How to read properties file from Jenkins 2.0 pipeline script I found the following code to work:

configFileProvider([configFile(fileId: "$PBD1_CONFIG", variable: 'configFile')]) {
     def props = readProperties file: "$configFile"
     def skip_tests = props['skip_tests']
     if (skip_tests == 'true') {
        print 'skipping tests'
     } else {
        print 'running tests'
     }
}

I had to use readProperties from Jenkins' Pipeline Utility Steps Plugin.

Solution 2

Since the file is in property format you can use it in a shell step:

sh """
  source ${MY_CONFIG}
  .
  .
  .
"""

You would need to export the properties that need to be available on programs that the shell calls (e.g. Maven)

Share:
14,403
Robert
Author by

Robert

I'm a lead frontend web developer, architect currently working with Angular, Stencil and all the other SPA related technologies.

Updated on June 24, 2022

Comments

  • Robert
    Robert almost 2 years

    I want to parametrize my Jenkins pipeline with a simple properties config file

    skip_tests=true
    

    that I've added to Jenkins Config File Managment:

    config file management screenshot

    In my pipeline I'm importing this file and try to read from it using the Jenkins Pipeline Config File Plugin.

    node('my-swarm') {
    
     MY_CONFIG = '27206b95-d69b-4494-a430-0a23483a6408'
    
     try {
    
         stage('prepare') {
             configFileProvider([configFile(fileId: "$MY_CONFIG", variable: 'skip_tests')]) {
                 echo $skip_tests
                 assert $skip_tests == 'true'
             }
         }
     } catch (Exception e) {
         currentBuild.result = 'FAILURE'
         print e
     }
    }
    

    This results in an error:

    provisioning config files...
    copy managed file [my.properties] to file:/home/jenkins/build/workspace/my-workspace@tmp/config7043792000148664559tmp
    [Pipeline] {
    [Pipeline] }
    Deleting 1 temporary files
    [Pipeline] // configFileProvider
    [Pipeline] }
    [Pipeline] // stage
    [Pipeline] echo
    groovy.lang.MissingPropertyException: No such property: $skip_tests for 
    class: groovy.lang.Binding
    

    Any ideas what I'm doing wrong here?

  • Robert
    Robert almost 5 years
    Thanks Rich! I'll try that if I don't find an easier way to get to the properties via configFileProvider.
  • Robert
    Robert almost 5 years
    Thanks @yong - this helped me finding the solution.
  • Robert
    Robert almost 5 years
    Rich, I didn't manage to export the properties and read them from the pipeline shell. Maybe you could refine your answer in a way that this becomes more clear. Besides that, I meanwhile found a solution using the Pipeline Utility Steps Plugin. I've documented it in another answer.