Jenkins + Build Flow, how to pass a variable from one job to another

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 14:47:55

问题


I have a build flow scenario similar to the documentation example: two jobs, one running after the other.

b = build("job1")
build("job2", param1: b.????)

My job1 is a shell script that builds a package out of a checked out git repositoy and prints out the version of the built package.

I need to extract the version from job1 (parse output??) and make it available somehow as a parameter to job2. How can this be achieved? Please note that I can't know the version before running job1.


回答1:


The problem with simply using export in a shell script build step is that the exported variables disappear when the shell script exits, they are not propagated up to the job.

Use the EnvInject plugin to create environment variables in your build. If you write out a properties file as part of your build, EnvInject can read the file and inject variables as a build step. A properties file has a simple KEY=VALUE format:

MY_BUILD_VERSION=some_parsed_value

Once you have an environment variable set in your job, in the Build Flow plugin, you can extract the variable's value and use it in subsequent jobs:

def version = build.environment.get( "MY_BUILD_VERSION" )
out.println String.format("Parameters: version: %s", version)
build( "My Second Build", MY_BUILD_VERSION: version )



回答2:


When you run job1 export the version with name as system property.

export appVersion="stringOfVersion-123"

Then it depend if you know how long is version (count of numbers or others characters). If you know it you can parse variable from end in second build as new variable and use it.

How parse string you can find in this question with nice examples.




回答3:


If job2 always should get some information from job1 you could use approach without parameters. job1 could publish artifact with version and job2 will use that artifact (with Copy Artifact Plugin for example). With that approach job2 could be executed also as standalone job.




回答4:


For anyone else coming upon this, another solution is to use a scriptler script, where you pass in the .properties file path, and the script will add the properties to the list of job variables:

Properties properties = new Properties()

FilePath workspace = build.getWorkspace()
FilePath sourceFile = workspace.child(path)

properties.load(sourceFile.read())

properties.each { key, value ->
  key = key.replace(".", "_").toUpperCase()
  Job.setVariable(build, key, value)

  println "Created Variable: " + key + "=" + value
}

This will convert any periods to underscores, and capitalize all letters. Using a scriptler script ensures that you have a method that works independent of the "plugin soup" you are using.



来源:https://stackoverflow.com/questions/26508444/jenkins-build-flow-how-to-pass-a-variable-from-one-job-to-another

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