[英]Jenkins Pipeline read from yaml
How do I read data from YAML file that is read in one stage and use it in another stage or outside the stage? 如何从一个阶段读取的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'
}
}
}
}
I want to access the ${datas.version} inside steps of Stage 2
that was fetched in Stage 1
. 我想访问在Stage 1
中获取的Stage 2
内部的$ {datas.version}。
I want to keep my pipeline definition as declarative as possible. 我希望尽可能将我的管道定义保持为声明性。 If i read the docs correctly, the script section can only be added within a stage. 如果我正确阅读文档 ,脚本部分只能添加到一个阶段。 I tried this on the global pipeline level but got an error Undefined section "script" at line 10
. 我在全局管道级别尝试了这个,但Undefined section "script" at line 10
得到了一个错误Undefined section "script" at line 10
。
I added just datas = readYaml file: 'release.yml'
at the pipeline level but get an error saying Not a valid section definition: "datas = readYaml file: 'release.yml'". Some extra configuration is required line 10, column 3.
我在管道级别添加了datas = readYaml file: 'release.yml'
但是得到错误说明Not a valid section definition: "datas = readYaml file: 'release.yml'". Some extra configuration is required line 10, column 3.
Not a valid section definition: "datas = readYaml file: 'release.yml'". Some extra configuration is required line 10, column 3.
What would be the correct way to reading the file once and then using that read data in any of the stages? 读取文件一次然后在任何阶段使用读取数据的正确方法是什么?
It seems I need a node
section around the readYaml
code. 看来我需要一个围绕readYaml
代码的node
部分。 Then I can access the ${datas.version}
in all the stages. 然后我可以在所有阶段访问${datas.version}
。
node {
datas = readYaml file: 'release.yml'
}
pipeline {
...
}
This is an issue being tracked JENKINS-40167 这是跟踪JENKINS-40167的问题
This is just a scope problem. 这只是一个范围问题。 If you declare your variable ( datas
) in a script block, it only exists in the scope of that block. 如果在脚本块中声明变量( datas
),则它仅存在于该块的范围内。
There are 2 ways to solve this. 有两种方法可以解决这个问题。 You can explicitly declare the variable "globally" (not truly global, terms of Groovy, as I understand it) by declaring it outside of the pipeline. 您可以通过在管道外声明它来显式声明变量“全局”(不是真正的全局,Groovy的术语,据我理解)。 Or with pipeline, if you don't declare a variable in a script, but just use it, it gets created as a "global" variable. 或者使用管道,如果您没有在脚本中声明变量,而只是使用它,则会将其创建为“全局”变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.