无法在null对象上调用getLastSuccessfulBuild()方法

时间:2017-09-15 12:42:25

标签: jenkins groovy groovy-console

无法通过Groovy脚本检索Jenkins作业最后成功的作业变量或参数,以便我可以将这些作为变量传递给下一个作业。

import jenkins.model.Jenkins
def job = Jenkins.instance.getJob("Testing-4")
def run = instance.getItems()
println run.getEnvironment()["PipelineId"]

错误日志

    ERROR: Build step failed with exception
java.lang.NullPointerException: Cannot invoke method getLastBuild() on null object
    at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:77)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:32)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at Script1.run(Script1.groovy:3)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:580)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:618)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:589)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript.evaluate(SecureGroovyScript.java:168)
    at hudson.plugins.groovy.SystemGroovy.run(SystemGroovy.java:95)
    at hudson.plugins.groovy.SystemGroovy.perform(SystemGroovy.java:59)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:782)
    at hudson.model.Build$BuildExecution.build(Build.java:205)
    at hudson.model.Build$BuildExecution.doRun(Build.java:162)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
    at hudson.model.Run.execute(Run.java:1738)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:410)

2 个答案:

答案 0 :(得分:0)

来自JavaDoc for Jenkins.getItem()

  

返回:一个项目   其Item.getName()name且其Item.getParent()this,或   null如果没有这样的项目,或者只有当前用户缺少   Item.DISCOVERItem.READ

对于您,getItem("Testing-4")正在返回null,因此没有名称为"Testing-4"的项目,或者您没有以具有相应权限的用户身份登录。

您可以获取getItems()项目列表,这些项目在探索性脚本中非常有用,可以找出您可以使用的项目。

答案 1 :(得分:0)

import hudson.model.*;

def lastSuccessfulPipelineID = build.getProject().getLastSuccessfulBuild().properties.get("envVars")['PipelineNumber']
def pa = new ParametersAction([
  new StringParameterValue("lastSuccessfulPipelineID", lastSuccessfulPipelineID)
])
println(lastSuccessfulPipelineID)

build.addAction(pa)