You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

声明式Jenkins流水线不同节点并行步骤无法访问全局作用域变量

问题原因

  • Groovy 语法中,使用 def 关键字在脚本顶层声明的变量属于脚本局部变量,不会被自动纳入流水线的全局绑定上下文,自定义函数 doParallelStuff 以及内部的闭包执行时,作用域内找不到该变量定义,因此抛出 MissingPropertyException 异常。
  • 你给出的示例代码中还存在 tests 变量未提前声明初始化的问题,实际运行也会触发同类异常。

可行解决方案

方案1:修改变量声明方式,使用全局绑定变量

去掉变量前的 def 关键字,Jenkins 流水线中不带 def 声明的顶层变量会被存入全局绑定属性,所有函数、闭包都可以直接访问:

// 去掉def,声明为全局绑定变量
script = """\
#/bin/bash
python xyz.py
"""
// tests也同样声明为全局绑定,或者在函数内部初始化
tests = [:]

def doParallelStuff() {
  tests["1"] = {
    node {
      stage('ps1') {
        sh script
      }
    }
  }

  tests["2"] = {
    node {
      stage('ps2') {
        sh script
      }
    }
  }
  parallel tests
}

pipeline {
  stages {
    stage("myStage") {
      steps {
        script {
          sh script
          doParallelStuff()
        }
      }
    }
  }
}

方案2:通过参数传递变量,避免全局变量污染

如果不想滥用全局变量,可以把需要共享的变量作为参数传入自定义函数,作用域更清晰,更符合编码规范:

def script = """\
#/bin/bash
python xyz.py
"""

// 函数增加入参接收需要的变量
def doParallelStuff(String scriptContent) {
  def tests = [:]
  tests["1"] = {
    node {
      stage('ps1') {
        sh scriptContent
      }
    }
  }

  tests["2"] = {
    node {
      stage('ps2') {
        sh scriptContent
      }
    }
  }
  parallel tests
}

pipeline {
  stages {
    stage("myStage") {
      steps {
        script {
          sh script
          // 调用时传入script变量
          doParallelStuff(script)
        }
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者David Schumann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 22:51:03