Jenkins 声明式管道:如何注入属性
Jenkins Declarative Pipeline: How to inject properties
我有带管道的 Jenkins 2.19.4:声明代理 API 1.0.1。如果您不能定义一个变量来分配读取的属性,如何使用 readProperties?
例如,要捕获 SVN 修订号,我目前使用以下脚本样式捕获它:
```
echo "SVN_REVISION=$(svn info ${svnUrl}/projects | \
grep Revision | \
sed 's/Revision: //g')" > svnrev.txt
```
def svnProp = readProperties file: 'svnrev.txt'
然后我可以访问使用:
${svnProp['SVN_REVISION']}
既然声明式定义svnProp是不合法的,那么readProperties如何使用?
您可以使用 steps
标记内的 script
步骤来 运行 任意管道代码。
所以在以下几行中:
pipeline {
agent any
stages {
stage('A') {
steps {
writeFile file: 'props.txt', text: 'foo=bar'
script {
def props = readProperties file:'props.txt';
env['foo'] = props['foo'];
}
}
}
stage('B') {
steps {
echo env.foo
}
}
}
}
这里我使用 env 在阶段之间传播值,但也可以采用其他解决方案。
需要授予脚本批准,因为它正在设置环境变量。 运行在同一阶段时不需要。
pipeline {
agent any
stages {
stage('A') {
steps {
writeFile file: 'props.txt', text: 'foo=bar'
script {
def props = readProperties file:'props.txt';
}
sh "echo $props['foo']"
}
}
}
}
要定义适用于所有阶段的通用变量,请将 props.txt
中的值定义为:
version=1.0
fix=alfa
并将脚本和声明性 Jenkins 管道混合为:
def props
def VERSION
def FIX
def RELEASE
node {
props = readProperties file:'props.txt'
VERSION = props['version']
FIX = props['fix']
RELEASE = VERSION + "_" + FIX
}
pipeline {
stages {
stage('Build') {
echo ${RELEASE}
}
}
}
我有带管道的 Jenkins 2.19.4:声明代理 API 1.0.1。如果您不能定义一个变量来分配读取的属性,如何使用 readProperties?
例如,要捕获 SVN 修订号,我目前使用以下脚本样式捕获它:
```
echo "SVN_REVISION=$(svn info ${svnUrl}/projects | \
grep Revision | \
sed 's/Revision: //g')" > svnrev.txt
```
def svnProp = readProperties file: 'svnrev.txt'
然后我可以访问使用:
${svnProp['SVN_REVISION']}
既然声明式定义svnProp是不合法的,那么readProperties如何使用?
您可以使用 steps
标记内的 script
步骤来 运行 任意管道代码。
所以在以下几行中:
pipeline {
agent any
stages {
stage('A') {
steps {
writeFile file: 'props.txt', text: 'foo=bar'
script {
def props = readProperties file:'props.txt';
env['foo'] = props['foo'];
}
}
}
stage('B') {
steps {
echo env.foo
}
}
}
}
这里我使用 env 在阶段之间传播值,但也可以采用其他解决方案。
pipeline {
agent any
stages {
stage('A') {
steps {
writeFile file: 'props.txt', text: 'foo=bar'
script {
def props = readProperties file:'props.txt';
}
sh "echo $props['foo']"
}
}
}
}
要定义适用于所有阶段的通用变量,请将 props.txt
中的值定义为:
version=1.0
fix=alfa
并将脚本和声明性 Jenkins 管道混合为:
def props
def VERSION
def FIX
def RELEASE
node {
props = readProperties file:'props.txt'
VERSION = props['version']
FIX = props['fix']
RELEASE = VERSION + "_" + FIX
}
pipeline {
stages {
stage('Build') {
echo ${RELEASE}
}
}
}