首页 > 解决方案 > Jenkins 声明式管道:触发管道中的特定阶段

问题描述

我正在使用 Jenkins 声明式管道,想知道是否有任何方法可以仅定期触发特定阶段。

我的意思是当我们检查 SCM 时,管道触发,但第 2 阶段对于我们的某些项目来说花费的时间太长。因此,与其等待这个阶段,我只想每天运行这个阶段,但仍将这个阶段保留在 jenkinsfile 中。

有什么办法可以做到这一点?这样做的最佳方法可能是什么?

    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
                )
            }
        }
    }

标签: jenkinsjenkins-pipelinejenkins-declarative-pipeline

解决方案


请参阅下面的代码/方法,它将让您了解如何在特定日期或特定条件下执行特定阶段。您可以根据您的要求更改条件
使用插件时间戳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 管道中可以使用 Triggeres 指令,如下所示,您可以在其中放置 cron 条件,但它将针对所有阶段而不是单个阶段执行。

// Declarative //
pipeline {
    agent any
    triggers {
        cron('H H 0 0 0')
    }
    stages {
        stage('Stage 1') {
        steps {
            script {
                  // do something
                )
            }
        }
      }
    }
}

推荐阅读