我有一個非常簡單的宣告性 Jenkins 檔案,它使用 cURL 從 API 檢索組態檔,然后使用 diff 命令查看它們是否與存盤庫中的相同組態檔不同。如果檢索的組態檔不同,我想替換舊檔案并提交新檔案。
我似乎無法弄清楚如何存盤一個值(例如 $CONFIG_CHANGED = YES)并在下一階段/步驟中使用它。理想情況下,如果配置沒有更改,我想跳過幾個階段,但我不知道如何在管道中重用變數。我用谷歌搜索了很多,但似乎環境變數是不可變的,無法在管道中更改。也許有一個我沒有看到的非常簡單的方法?我會很感激一些正確方向的指示。
uj5u.com熱心網友回復:
第一部分將解釋如何提取 shell 腳本中設定的值。然后我將解釋如何有條件地運行一個階段。
以下是一些可以從 shell 執行中提取值的方法。
- 執行腳本并讀取標準。請注意,您寫入 STDOUT 的任何內容都將被附加并回傳。
res = sh (script: '''
# DO what ever you want here
CONFIG_SET="YES"
echo "1234"
echo $CONFIG_SET''', returnStdout: true).trim()
echo "$res"
- 回傳退出狀態。在這里,您可以回傳退出代碼,而不是回傳 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"
- 寫入檔案并讀取檔案。
sh (script: '''
# DO what ever you want here
CONFIG_SET="NO"
echo $CONFIG_SET > output
''')
res3 = readFile('output').trim()
echo "$res3"
提取值后,您可以定義一個新階段并使用 when{} 添加條件檢查。以下是完整的管道。
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"
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489943.html
標籤:詹金斯 詹金斯管道 jenkins-groovy cicd
