我正在使用 Jenkins 声明式流水线,想知道是否有任何方法可以仅定期触发特定阶段。
我的意思是,当我们检查 SCM 时,管道会触发,但对于我们的某些项目来说,第 2 阶段花费的时间太长。因此,与其等待这个阶段,我只想每天运行这个阶段,但仍将此阶段保留在 jenkinsfile 中。< /p>
有什么办法可以做到这一点吗?这样做的最佳方法是什么?
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
triggers {
cron('H H 0 0 0')
}
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
steps {
script {
// do something
)
}
}
}
答案 0 :(得分:2)
请参阅下面的代码/方法,它会让您了解如何在特定日期或特定条件下执行特定阶段。您可以根据需要更改条件
使用插件时间戳 https://plugins.jenkins.io/timestamper/ 获取时间戳相关信息。
# Get the day from the build timestamp
def getday = env.BUILD_TIMESTAMP
getday = getday .split(" ")
// Extract current day
getday = getday [3]
pipeline
{
agent any
options { timestamps () }
stages {
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
stage('Stage 2') {
when
{
// Note: You can change condition as per your need
// Stage will run only when the day is Mon
expression {
getday == "Mon"
}
}
steps {
script {
// do something
)
}
}
}
}
配置 BuildTimestamp:
如果您的构建时间戳未配置为获取日期信息,则可以使用以下方法
https://plugins.jenkins.io/build-timestamp/
管理 Jenkins -> 配置系统 -> 构建时间戳 -> 点击启用 BUILD_TIMESTAMP。
将模式设为:yyyy-MM-dd HH:mm:ss z EEE
请注意:触发器指令在 jenkins 管道中可用,如下所示,您可以在其中放置您的 cron 条件,但它将在所有阶段而不是单个阶段执行。
// Declarative //
pipeline {
agent any
triggers {
cron('H H 0 0 0')
}
stages {
stage('Stage 1') {
steps {
script {
// do something
)
}
}
}
}
}