我正在尝试使用声明性管道语法从input
步骤访问变量,但似乎无法通过env
或params
访问该变量。
这是我的阶段定义:
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)
访问此选项参数的正确方法是什么?
答案 0 :(得分:38)
由于您使用的是声明性管道,我们需要做一些技巧。通常您从输入阶段保存返回值,如此
def returnValue = input message: 'Need some input', parameters: [string(defaultValue: '', description: '', name: 'Give me a value')]
但是,在声明性管道步骤中不允许这样做。相反,您需要做的是将input
步骤包装在script
步骤中,然后将值传播到适当的位置(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的片段生成器:
如果只列出一个参数,则其值将成为输入步骤的值。如果列出了多个参数,则返回值将是由参数名称键入的映射。如果未请求参数,则如果批准则该步骤不返回任何内容。
答案 1 :(得分:0)
@DavidParker,我已经弄清楚了您的要求。只需尝试在您的代码中使用它即可。我已经输入了参数,并按1乘1的方式使用它们。我在工作中仅打印“变量”键。您也可以尝试这种方式。
steps{
script {
deploymentParams.findAll{ key, value -> key.startsWith('backendIP') }.each { entry ->
stage("Node_$entry.key "){
echo $entry.value
}
}
}
}