如何使用命令的结果来决定詹金斯阶段是否应该执行?



我有一个非常简单的声明式Jenkins文件,它使用cURL从API检索配置文件,然后使用diff命令查看它们是否与存储库中的相同配置文件不同。如果检索配置文件是不同的,我想替换旧的文件,并提交新的。

我似乎不知道如何存储一个值(例如$CONFIG_CHANGED = YES)并在下一阶段/步骤中使用它。理想情况下,如果配置没有改变,我想跳过几个阶段,但我不知道如何在管道中重用变量。我在谷歌上搜索了很多,但似乎环境变量是不可变的,不能在管道中更改。也许有一种我没发现的简单方法?如果你能给我指点一下方向,我会很感激的。

第一部分将解释如何在shell脚本中提取值集。然后我将解释如何有条件地运行阶段。

下面是几种从shell执行中提取值的方法。

  1. 执行脚本并读取标准。注意,写入STDOUT的内容将被追加并返回。
res = sh (script: '''
# DO what ever you want here
CONFIG_SET="YES"
echo "1234"
echo $CONFIG_SET''', returnStdout: true).trim()
echo "$res"
  1. 返回退出状态。这里,您可以返回退出代码,而不是返回STDOUT。你可以这样创建一个shell脚本,它可以检查参数并返回正确的退出状态。
res2 = sh (script: '''
# DO what ever you want here
CONFIG_SET="NO"
if [ $CONFIG_SET == "YES" ]
then
exit 0
else
echo "1111"    
exit 1
fi
''', returnStatus: true) == 0
echo "$res2"
  1. 写入文件并读取文件
sh (script: '''
# DO what ever you want here
CONFIG_SET="NO"
echo $CONFIG_SET > output
''')
res3 = readFile('output').trim()
echo "$res3"

提取值后,您可以定义一个新的阶段,并添加一个条件检查when{}。以下是完整的Pipeline。

def res2 = false
pipeline {
agent any
stages {
stage('Hello') {
steps {
script {
res = sh (script: '''
# DO what ever you want here
CONFIG_SET="YES"
echo "1234"
echo $CONFIG_SET''', returnStdout: true).trim()
echo "$res"

res2 = sh (script: '''
# DO what ever you want here
CONFIG_SET="YES"
if [ $CONFIG_SET == "YES" ]
then
exit 0
else
echo "1111"    
exit 1
fi
''', returnStatus: true) == 0
echo "$res2"


sh (script: '''
# DO what ever you want here
CONFIG_SET="NO"
echo $CONFIG_SET > output
''')
res3 = readFile('output').trim()
echo "$res3"

def type = res.class
}
}
}
stage('IFYES') {
when { expression { return res2} }
steps {
echo "Executing"
}
}
}
}

最新更新