如何在 Jenkins 的中央共享库中定义参数

问题描述 投票:0回答:1

我使用 jenkins 版本 2.440.2,我希望能够在共享库等中心位置定义所有参数,并在不同的 jenkins 文件中重用这些参数配置。

// vars/commonParams.groovy
def getParams() {
    return [
        string(name: 'ENVIRONMENT', defaultValue: 'dev', description: 'Environment to deploy to'),
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
    ]
}


// Jenkinsfile
@Library('my-shared-library') _
def param = commonParams.getParams()

pipeline {
    agent any
    parameters { param }
    stages {
        stage('Build') {
            steps {
                echo "Environment: ${params.ENVIRONMENT}"
                echo "Run Tests: ${params.RUN_TESTS}"
            }
        }
    }
}

这会引发错误

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 10: Expected a build parameter definition @ line 10, column 9.
           param
           ^

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)
    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1107)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:624)
    at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:602)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:579)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:323)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:293)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox$Scope.parse(GroovySandbox.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:190)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:175)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:635)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:581)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:335)
    at hudson.model.ResourceController.execute(ResourceController.java:101)
    at hudson.model.Executor.run(Executor.java:442)
Finished: FAILURE
jenkins jenkins-pipeline jenkins-groovy jenkins-shared-libraries
1个回答
0
投票
发生错误是因为 Jenkins 的参数块需要单独的

parameter

 定义,而不是列表。你不能像
parameters { param }
那样直接传递参数列表。为了解决这个问题,您可以使用循环将共享库中的每个参数添加到参数块中。

@Library('my-shared-library') _ pipeline { agent any parameters { // Loop through each parameter returned by the shared library commonParams.getParams().each { param -> parameter param } } stages { stage('Build') { steps { echo "Environment: ${params.ENVIRONMENT}" echo "Run Tests: ${params.RUN_TESTS}" } } } }
    
© www.soinside.com 2019 - 2024. All rights reserved.