Jenkins-pipeline Extract and Set variables from properties file in groovy

十年热恋 提交于 2019-12-03 21:54:49

问题


To begin i'm writing the pipeline entirely as groovy to be checked in to git. Please do not provide any gui necessary solutions. My Problem statement is:

Extract a variable from a file and set it equal to a groovy object.

What i've tried

def SERVICE_MAJOR_VERSION
node {
    runGitClone(GIT_REPO_URL, GIT_HASH)
    def conf = readFile("gradle.properties")
    echo conf
    //THE BELOW COMMENT DOESN'T WORK
    //SERVICE_MAJOR_VERSION = loadEnvFromFile("SERVICE_VERSION_MAJOR", "gradle.properties", true, SERVICE_VERSION_MAJOR)
}    

def runGitClone(git_repo_url, git_hash) {
    checkout changelog: false, poll: false, scm: [$class: 'GitSCM', branches: [[name: git_hash]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'WipeWorkspace']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '85572032-4284-4095-9eec-4df70ddfdb68', url: git_repo_url]]]
}

def loadEnvFromFile(string_name, file_path, should_print_load) {
    def par1 = null
    def content = readFile file_path
    def matcher = content =~ /${string_name}\=(.+)/
    if (matcher) {
        par1 = string_name + "='" + matcher[0][1] + "'"
        new GroovyShell(this.binding).evaluate(par1)
            if (should_print_load) {
            println par1
        }
    }
    return par1
}

I've tried other suggestions to no avail. Particularly the below two.

  • Get values from properties file using Groovy
  • Parsing string as properties

If you have a working example of extracting a variable from a file and setting it equal to a groovy object it would solve my problem.


回答1:


SOLVED:

def content = readFile 'gradle.properties'

Properties properties = new Properties()
InputStream is = new ByteArrayInputStream(content.getBytes());
properties.load(is)

def runtimeString = 'SERVICE_VERSION_MINOR'
echo properties."$runtimeString"
SERVICE_VERSION_MINOR = properties."$runtimeString"
echo SERVICE_VERSION_MINOR


来源:https://stackoverflow.com/questions/38954913/jenkins-pipeline-extract-and-set-variables-from-properties-file-in-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!