从 yaml 读取的 Jenkins 管道

soundcode 阅读:35 2025-06-02 22:19:02 评论:0

如何从一个阶段读取的 YAML 文件中读取数据并在另一个阶段或阶段外使用它?

pipeline { 
  agent any 
  environment { 
    MY_ENV_VAR1 = 'VALUE1' 
  } 
  parameters { 
    string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: 'Environment to deploy on') 
    booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: 'Debug the build') 
  } 
  stages { 
    stage('Stage1') { 
      steps { 
        script { 
          def datas = readYaml file: 'release.yml' 
          echo "Got version as ${datas.version} " 
        } 
        echo "Deploying to ${params.DEPLOY_ENV} with debug=${params.DEBUG_BUILD}" 
      } 
    } 
    stage('Stage 2') { 
      steps { 
        sh 'run.sh datas.version' 
      } 
    } 
  } 
} 

我想在 Stage 2 的步骤中访问 ${datas.version}这是在 Stage 1 中提取的.

我想让我的管道定义尽可能具有声明性。
如果我阅读了 docs正确,脚本部分只能添加到一个阶段中。我在全局管道级别尝试过此操作,但出现错误 Undefined section "script" at line 10 .

我只加了 datas = readYaml file: 'release.yml'在管道级别但收到错误消息 Not a valid section definition: "datas = readYaml file: 'release.yml'". Some extra configuration is required line 10, column 3.
读取文件一次然后在任何阶段使用读取数据的正确方法是什么?

请您参考如下方法:

看来我需要一个 node节左右readYaml代码。然后我可以访问${datas.version}在所有阶段。

node { 
  datas = readYaml file: 'release.yml' 
} 
pipeline { 
 
... 
} 

这是一个正在跟踪的问题 JENKINS-40167


标签:Jenkins
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号