Jenkins声明性管道:如何从输入步骤中读取选择?

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

我正在尝试使用声明性管道语法从input步骤访问变量,但似乎无法通过envparams获得。这是我的舞台定义:

stage('User Input') {
    steps {
        input message: 'User input required', ok: 'Release!',
            parameters: [choice(name: 'RELEASE_SCOPE', choices: 'patch\nminor\nmajor', description: 'What is the release scope?')]
        echo "env: ${env.RELEASE_SCOPE}"
        echo "params: ${params.RELEASE_SCOPE}"
    }
}

两个echo步骤打印null。我也尝试直接访问变量但是我收到以下错误:

groovy.lang.MissingPropertyException: No such property: RELEASE_SCOPE for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)

访问此选项参数的正确方法是什么?

jenkins jenkins-pipeline
1个回答
38
投票

由于您使用的是声明性管道,我们需要做一些技巧。通常,您可以保存输入阶段的返回值,如下所示

def returnValue = input message: 'Need some input', parameters: [string(defaultValue: '', description: '', name: 'Give me a value')]

但是,这不能直接在声明性管道步骤中使用。相反,你需要做的是将input步骤包装在script步骤中,然后将值传播到approprierte位置(env似乎工作正常,请注意该变量暴露给管道的其余部分)。

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.RELEASE_SCOPE = input message: 'User input required', ok: 'Release!',
                            parameters: [choice(name: 'RELEASE_SCOPE', choices: 'patch\nminor\nmajor', description: 'What is the release scope?')]
                }
                echo "${env.RELEASE_SCOPE}"
            }
        }
    }
}

请注意,如果输入步骤中有多个参数,则输入将返回一个地图,您需要使用地图引用来获取所需的条目。来自Jenkins的代码段生成器:

如果仅列出一个参数,则其值将成为输入步骤的值。如果列出了多个参数,则返回值将是由参数名称键入的映射。如果未请求参数,则如果批准则该步骤不返回任何内容。

© www.soinside.com 2019 - 2024. All rights reserved.