Groovy根据作业值的JSON生成动态参数?

时间:2016-11-21 04:28:06

标签: json jenkins groovy hudson

我刚刚通过JSON URL找到Jenkins的工作,每个作业都使用这种格式:https://jenkinsurl.net/job/_test/lastBuild/api/json提供如下信息。

{"_class":"hudson.model.FreeStyleBuild","actions":[{"_class":"hudson.model.ParametersAction","parameters":[{"_class":"hudson.model.StringParameterValue","name":"build_num","value":""}]},{"_class":"hudson.model.CauseAction","causes":[{"_class":"hudson.model.Cause$UserIdCause","shortDescription":"Started by user anonymous","userId":"anonymous","userName":"anonymous"}]},{},{},{},{},{},{"_class":"org.jenkinsci.plugins.buildenvironment.actions.BuildEnvironmentBuildAction"},{}],"artifacts":[],"building":false,"description":null,"displayName":"#1","duration":1850,"estimatedDuration":1850,"executor":null,"fullDisplayName":"_test #1","id":"1","keepLog":false,"number":1,"queueId":5753,"result":"SUCCESS","timestamp":1479700053274,"url":"http://jenkinsserver.net/job/_test/1/","builtOn":"node_name","changeSet":{"_class":"hudson.scm.EmptyChangeLogSet","items":[],"kind":null},"culprits":[]}

我想知道如何使用Groovy脚本查询这些字段,以帮助我在选择“使用参数构建”时构建动态参数。我已经有了Groovy和Dynamic参数插件,并将它们用于我一直用来生成一些参数的简单查询,比如Jenkins作业下游没有覆盖的时间戳。

如何查询这些并返回其值?例如,如果我想从此段返回启动构建的用户的值:

[{"_class":"hudson.model.Cause$UserIdCause","shortDescription":"Started by user anonymous","userId":"anonymous","userName":"anonymous"}]

这不是关于让触发构建的人的问题。很抱歉,如果这不是一个很好的例子,但这个似乎有点嵌套,所以可能是一个很好的学习。

我知道如何引用参数的值并获取一些信息以返回生成它们,但不知道如何使用该URL并从中提取特定信息以帮助在构建开始之前创建参数值。这可能吗?如果没有,我可以使用其他机制吗?

1 个答案:

答案 0 :(得分:0)

您可以执行与此类似的操作: How do I discover the additional causes of my Jenkins build?

job = hudson.model.Hudson.instance.getItem("demo-job")
build = job.getLastBuild()

// get action first
def action = build.getAction(hudson.model.CauseAction.class)    
cause = action.findCause(hudson.model.Cause.UserIdCause)
println cause.userId

http://javadoc.jenkins-ci.org/hudson/model/Cause.UserIdCause.html

问题是令人困惑,所以不确定这是否有帮助。无论如何,您应该能够从 getLastBuild()返回的构建中提取所需的所有信息。

在构建开始之前,不可能有额外的参数。如果这就是你的意思。