通过 Jenkinsfile 中的变量从特定分支导入库

Ewr*_*wro 6 shared-libraries jenkins jenkins-pipeline

我想在 Jenkinsfile 中隐式加载共享库,而不是动态加载,但从每个变量中为共享库选择特定分支。出于测试目的,我尝试在每个属性变量的 @library 语句中插入变量。如果我直接在里面写分支名称,它会起作用。

#!/usr/bin/env groovy
properties([
    stringParam(name: 'BRANCH_NAME', defaultValue: 'master')
  ])
])

@Library("custom-shared-library@${params.BRANCH_NAME}")

import com.custom.test.utils.*

println("hello world!")
Run Code Online (Sandbox Code Playgroud)

收到以下错误消息:

WorkflowScript: @Library value ‘custom-shared-library@$params.BRANCH_NAME’ was not a constant; did you mean to use the ‘library’ step instead?

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
    at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
    at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:131)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:125)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:560)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:521)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:319)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:429)
Finished: FAILURE
Run Code Online (Sandbox Code Playgroud)

是否可以在@library()语句中插入变量?

Yur*_* G. 6

对于脚本化管道,请参阅https://jenkins.io/doc/book/pipeline/shared-libraries/#loading-libraries-dynamically 上的文档

properties([parameters([string(name: 'LIB_VERSION', defaultValue: 'master')])])
library "my-shared-library@${params.LIB_VERSION}"
Run Code Online (Sandbox Code Playgroud)

对于声明性管道使用libraries指令,如此处所述https://github.com/cloudbees/intro-to-declarative-pipeline/blob/master/Exercise-04.md

libraries {
  lib("my-shared-library@${params.LIB_VERSION}")
}
Run Code Online (Sandbox Code Playgroud)

libraries指令已添加1.1管道模型定义插件的版本中。但出于某种原因,我没有在管道语法文档中看到它。