我有将脚本移植到声明性管道的问题。我曾经在脚本中://脚本
def myEnv = [:]
stage ('Prepare my env') { [...] myEnv = ... }
stage ('Fancy stuff') {
node() {
withEnv(myEnv) {
// here use what is defined in myEnv
}
}
stage ('Fancy stuff2') {
node() {
withEnv(myEnv) {
// here use what is defined in myEnv
} }
}
现在在声明中,我想
//声明性的
def myEnv = [:]
pipeline {
agent none
stage('Prepare my env') {
steps {
script {
[...]
myEnv = ...
}
}
}
stages {
environment { myEnv }
stage('Fancy stuff') {
[...]
}
stage('Fancy stuff2') {
[...]
}
} }
当我尝试运行它时,它失败了 Env
org.codehaus.groovy.control.MultipleCompilationErrorsException:启动失败:WorkflowScript:xx:“myEnv”不是有效的环境表达式。将“key=value”对与有效的Java/shell键一起使用。
很公平。我应该怎么做才能使用声明性环境{},以避免在以后的步骤中使用withEnv(myEnv)?
似乎您缺少的部分是环境
条款的使用。
而不是
environment { myEnv }
它应该是
environment { myEnvVal = myEnv }
正如错误方法提到的,这应该是key = value对。
您的问题来自变量< code>myEnv的类型。当您< code>def myEnv = [:]时,您将它定义为一个映射。
因此,它适用于将映射作为参数的with Env
,但不适用于仅接受“key=value”语句的环境{…}
。
解决方案取决于您如何添加 myEnv
中包含的环境变量。
最简单的方法是使用environment
指令,列出前一个变量myEnv
中包含的所有键/值:
pipeline{
agent none
environment {
test1 = 'test-1'
test2 = 'test-2'
}
stages{
stage('Fancy stuff'){
steps{
echo "${test1}"
}
}
stage('Fancy stuff2'){
steps{
echo "${test2}"
}
}
}
}
但你也可以用脚本的方式来做:
pipeline{
agent none
stages{
stage('Prepare my env') {
steps {
script {
def test = []
for (int i = 1; i < 3; ++i) {
test[i] = 'test-' + i.toString()
}
test1 = test[1]
test2 = test[2]
}
}
}
stage('Fancy stuff'){
steps{
echo "${test1}"
}
}
stage('Fancy stuff2'){
steps{
echo "${test2}"
}
}
}
}