主动选择反应参数 Groovy 脚本从另一个作业读取工件

问题描述 投票:0回答:1
  • 我想要实现的目标:

我有一份工作 A,它会产生一个工件。该工件称为“result.json”

这是 result.json 的示例

[
  {
    "product": "banana",
    "from": "India",
    "price": "42"
  },
  {
    "product": "coconut",
    "from": "Thailand",
    "price": "1"
  },
  {
    "product": "Watermelon",
    "from": "Japan",
    "price": "1000"
  },
  {
    "product": "orange",
    "color": "Spain",
    "price": "5"
  }
]

请注意,result.json 不是静态文件。每个版本的内容都会发生变化。

我有一个工作 B,我想在其中创建一个参数列表,该列表来自管道 A 的“result.json”文件。

基本上,使用 Groovy 脚本创建主动选择反应参数。

  • 预期结果:

使用下面的代码,我希望填充参数。

  • 实际结果:

不幸的是,没有条目,似乎作业 B 无法从作业 A 中选取“result.json”。

  • 我尝试过的:
import groovy.json.JsonSlurper

def filedata = readFile(file: 'jobA.result.json')

def jsonParser = new JsonSlurper()
def data = jsonParser.parseText(filedata)
return data.fullName
  • 问题:

我确信“result.json”来自作业 A。

如何在 Active Choices Reactive Parameter Groovy 脚本中从作业 B 获取文件?

jenkins groovy jenkins-groovy
1个回答
0
投票

如果您想根据作业 A 生成的“

result.json
”工件在作业 B 中创建参数列表,则需要确保作业 B 可以访问作业 A 存储的工件。
这意味着“
result.json
”必须在作业 A 中存档并且可访问,并且
'jobA.result.json'
正确指向作业 A 中的存档工件。并且作业 B 必须有权访问作业 A 中的工件。

Job A   ┌─────────┐   result.json  ┌─────────┐   Job B
───────>│ Archive │───────────────>│ Read &  │───────>
        │ Artifact│<───────────────│ Parse   │<───────
        └─────────┘   Accessible?  └─────────┘

您可以在 Groovy 脚本中的 Active Choices Reactive Parameter 功能中使用。

import groovy.json.JsonSlurper
import hudson.FilePath
import jenkins.model.Jenkins

def jenkins = Jenkins.getInstance()
def jobA = jenkins.getItem("JobA")
def lastSuccessfulBuild = jobA.getLastSuccessfulBuild()
def artifact = lastSuccessfulBuild.getArtifactManager().root().child("result.json")
def filedata = new FilePath(artifact).readToString()

def jsonParser = new JsonSlurper()
def data = jsonParser.parseText(filedata)

// Assuming you want to create a string in the format "product-from-price"
def parameters = data.collect { "${it.product}-${it.from}-${it.price}" }
return parameters

该脚本旨在在 Jenkins 脚本控制台中运行,或者作为配置了脚本权限的作业的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.