Jenkins并行脚本使用错误的变量循环

时间:2019-01-15 01:37:00

标签: jenkins groovy

我正在尝试构建一组动态的步骤以并行运行。以下示例是我想出的(并在https://devops.stackexchange.com/questions/3073/how-to-properly-achieve-dynamic-parallel-action-with-a-declarative-pipeline中找到了示例)。但是我很难让它使用预期的变量。结果似乎总是来自循环的最后一次迭代的变量。

在以下示例中,两个测试的回波输出始终为bdir2

pipeline {
  agent any

  stages {
    stage('Test') {
      steps {
        script {
          def tests = [:]
          def files

          files = ['adir1/adir2/adir3','bdir1/bdir2/bdir3']

          files.each { f ->
            rolePath = new File(f).getParentFile()
            roleName = rolePath.toString().split('/')[1]

            tests[roleName] = {
              echo roleName
            }
          }

          parallel tests
        }
      }
    }
  }
}

我期望其中一个测试输出adir2,而另一个输出bdir2。我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

只需尝试将测试部分向上移动一点,它就会起作用

pipeline {
  agent any
  stages {
    stage('Test') {
      steps {
        script {
          def tests = [:]
          def files

          files = ['adir1/adir2/adir3','bdir1/bdir2/bdir3']

          files.each { f ->
            tests[f] = {
             rolePath = new File(f).getParentFile()
             roleName = rolePath.toString().split('/')[1]
             echo roleName
            }
          }
          parallel tests
        }
      }
    }
  }
}