Jenkins 管道抛出 java.io.NotSerializableException: org.jenkinsci.plugins.workflow.job.WorkflowRun 即使使用 @NonCPS

Eka*_*lbs 7 git groovy jenkins-pipeline

代码相当简单,我只想要一个 rev-list 发布到 slack。但是导致我出现问题的部分是当我实际上试图从 git 获取 rev-list 时。

问题代码

@NonCPS
def getRevisionList(currentCommit, lastSuccessfulCommit) {
     def commits = sh(
        script: "git rev-list $currentCommit $lastSuccessfulCommit",
        returnStdout: true
    ).split('\n')
    echo "$commits"
}
Run Code Online (Sandbox Code Playgroud)

完整代码:

@NonCPS
def getRevisionList(currentCommit, lastSuccessfulCommit) {
     def commits = sh(
        script: "git rev-list $currentCommit $lastSuccessfulCommit",
        returnStdout: true
    ).split('\n')
    echo "$commits"
}
Run Code Online (Sandbox Code Playgroud)

詹金斯给我的错误是这样的:

an exception which occurred:
in field com.cloudbees.groovy.cps.impl.BlockScopeEnv.locals
in object com.cloudbees.groovy.cps.impl.BlockScopeEnv@76bde0fe
in field com.cloudbees.groovy.cps.impl.CallEnv.caller
in object com.cloudbees.groovy.cps.impl.FunctionCallEnv@662f031a
in field com.cloudbees.groovy.cps.Continuable.e
in object org.jenkinsci.plugins.workflow.cps.SandboxContinuable@1156ea7f
in field org.jenkinsci.plugins.workflow.cps.CpsThread.program
in object org.jenkinsci.plugins.workflow.cps.CpsThread@5bada334
in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.threads
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@42bbb563
in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@42bbb563
Run Code Online (Sandbox Code Playgroud)

引起:java.io.NotSerializableException:org.jenkinsci.plugins.workflow.job.WorkflowRun

更多或更少我正在关注以下内容,但是我收到了错误。我曾尝试以原始方式运行它,但也没有任何运气。

Jenkinsfile - 获取构建之间的所有更改

Szy*_*iak 10

您看到的异常是由以下行引起的:

def currentBuild = currentBuild.rawBuild
Run Code Online (Sandbox Code Playgroud)

currentBuild.rawBuild返回一个不可序列化的对象,因此必须在@NonCPS方法内部调用以避免出现此异常。尝试简化您的辅助方法,以便它们访问currentBuild内部变量@NonCPS

@NonCPS
def getRevisionList(currentCommit, lastSuccessfulCommit) {
     def commits = sh(
        script: "git rev-list $currentCommit $lastSuccessfulCommit",
        returnStdout: true
    ).split('\n')
    echo "$commits"
}

@NonCPS
def getLastSuccessfulCommit() {
  def lastSuccessfulHash = null
  def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild()
  if ( lastSuccessfulBuild ) {
    lastSuccessfulHash = commitHashForBuild( lastSuccessfulBuild )
  }
  return lastSuccessfulHash
}

@NonCPS
def commitHashForBuild() {
    def scmAction = currentBuild?.rawBuild?.actions?.find { action -> action instanceof jenkins.scm.api.SCMRevisionAction }
    return scmAction?.revision?.hash
}
Run Code Online (Sandbox Code Playgroud)

currentBuild.rawBuild -hudson.model.Run带有更多 API 的,仅适用于沙箱外的受信任库或管理员批准的脚本;该值不会是,Serializable因此您只能在标记的方法中访问它@NonCPS


来源:https : //qa.nuxeo.org/jenkins/pipeline-syntax/globals#currentBuild