Jenkins声明性管道:如何从输入步骤中读取选择? [英] Jenkins Declarative Pipeline: How to read choice from input step?
问题描述
我正在尝试使用声明性管道语法从input
步骤访问变量,但似乎无法通过env
或params
使用.
这是我的舞台定义:
I'm trying to access a variable from an input
step using the declarative pipelines syntax but it seems not to be available via env
or params
.
This is my stage definition:
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
.我也尝试直接访问变量,但出现以下错误:
Both echo
steps print null
. I also tried to access the variable directly but I got the following error:
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)
访问此选择参数的正确方法是什么?
What is the correct way to access this choice parameter?
推荐答案
由于您使用的是声明式管道,因此我们需要做一些技巧.通常,您可以像这样保存输入阶段的返回值
Since you are using declarative pipelines we will need to do some tricks. Normally you save the return value from the input stage, like this
def returnValue = input message: 'Need some input', parameters: [string(defaultValue: '', description: '', name: 'Give me a value')]
但是,在声明式管道步骤中不允许直接这样做.相反,您需要做的是将input
步骤包装在script
步骤中,然后将值传播到适当的位置(env
似乎工作良好,请注意,尽管变量已暴露给管道的其余部分, ).
However this is not allowed directly in declarative pipeline steps. Instead, what you need to do is wrap the input
step in a script
step and then propagate the value into approprierte place (env
seems to work good, beware that the variable is exposed to the rest of the pipeline though).
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}"
}
}
}
}
请注意,如果在输入步骤中有多个参数,则输入将返回一个地图,并且您需要使用地图引用来获取所需的条目.在詹金斯的摘要生成器中:
Note that if you have multiple parameters in the input step, then input will return a map and you need to use map references to get the entry that you want. From the snippet generator in Jenkins:
如果仅列出一个参数,则其值将成为输入步骤的值.如果列出了多个参数,则返回值将是一个由参数名称作为键的映射.如果不要求参数,则该步骤在批准后不返回任何内容.
If just one parameter is listed, its value will become the value of the input step. If multiple parameters are listed, the return value will be a map keyed by the parameter names. If parameters are not requested, the step returns nothing if approved.
这篇关于Jenkins声明性管道:如何从输入步骤中读取选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!