是否可以在 Jenkins 共享库中使用构建用户变量插件?

Is it possible to use build user vars plugin in a Jenkins shared library?

我正在实现将 Jenkins 管道的触发用户公开到我们的 CD 系统的功能,因此我获取了构建用户 vars 插件:https://plugins.jenkins.io/build-user-vars-plugin/

插件的工作方式似乎是包装需要公开变量的代码,如下所示:

  wrap([$class: 'BuildUser']) {
    userId = env.BUILD_USER_ID
  }

我在一般管道上试过这个,只是回显出来,一切都很好。

然后我尝试在我们的共享库中实现它,以便在对 CD 的所有调用中发生这种情况,但我遇到了一个错误。

wrap([$class: 'BuildUser']) {
    jobBuildUrl ="${jobBuildUrl}&USER_ID=${env.BUILD_USER_ID}"
}

[2021-08-19T10:20:22.852Z] hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: com.company.jenkins.pipelines.BuildManager.wrap() is applicable for argument types: (java.util.LinkedHashMap, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [[$class:BuildUser], org.jenkinsci.plugins.workflow.cps.CpsClosure2@1c9a210c]

有没有办法在共享库中使用这个插件代码?如果有怎么办?

我不相信,但我认为值得一问。作为参考,有这个突出的问题:https://issues.jenkins.io/browse/JENKINS-44741

旁注,我正在尝试在不触及每个人的管道的情况下执行此操作。如果这个插件不可能做到这一点,我可能会在共享库中实现我自己的版本。

那个插件很难用而且有很多问题,其中之一就是共享库。
而不是自己实现它,它相对容易,并且允许您更好地控制完成的逻辑、错误处理以及您使用的参数 return.
您可以使用如下内容:

/**
* Get the last upstream build that triggered the current build
* @return Build object (org.jenkinsci.plugins.workflow.job.WorkflowRun) representing the upstream build
*/
@NonCPS
def getUpstreamBuild() {
   def build = currentBuild.rawBuild
   def upstreamCause
   while (upstreamCause = build.getCause(hudson.model.Cause$UpstreamCause)) {
       build = upstreamCause.upstreamRun
   }
   return build
}

/**
* Get the properties of the build Cause (the event that triggered the build)
* @param upstream If true (Default) return the cause properties of the last upstream job (If the build was triggered by another job or by a chain of jobs)
* @return Map representing the properties of the user that triggered the current build.
*         Contains keys: USER_NAME, USER_ID
*/
@NonCPS
def getUserCauseProperties(Boolean upstream = true) {
   def build = upstream ? getUpstreamBuild() : currentBuild.rawBuild
   def cause = build.getCause(hudson.model.Cause$UserIdCause)
   if (cause) {
       return ['USER_NAME': cause.userName, 'USER_ID': cause.userId]
   }
   println "Job was not started by a user, it was ${build.getCauses()[0].shortDescription}"
   return [:]
}