首页 > 解决方案 > 如何在 Jenkins 管道语法中对文件的最后修改时间使用`when`条件

问题描述

我正在创建一个 Jenkins 管道,我希望仅当特定日志文件(日志文件位于所有阶段都将运行的服务器节点中)最后修改日期在管道作业启动后更新时触发某个阶段,我知道我们需要使用“何时”条件,但不确定如何实现它。

尝试引用一些与管道相关的门户,但无法找到答案

有人可以帮我解决这个问题吗?

提前致谢!

标签: jenkinsjenkins-pipeline

解决方案


To get data about file is quite tricky in a Jenkins pipeline when using the Groovy sandbox since you're not allowed to do new File(...).lastModified. However there is the findFiles step, which basically returns a list of wrapped File objects with a getter for last modified time in millis, so we can use findFiles(glob: "...")[0].lastModified.

The returned array may be empty, so we should rather check on that (see full example below).

The current build start time in millis is accessible via currentBuild.currentBuild.startTimeInMillis.

Now that we git both, we can use them in an expression:

pipeline {

    agent any

    stages {

        stage("create file") {
            steps {
                touch "testfile.log"
            }
        }

        stage("when file") {
            when {
                expression {
                    def files = findFiles(glob: "testfile.log")
                    files && files[0].lastModified < currentBuild.startTimeInMillis
                }
            }
            steps {
                echo "i ran"
            }
        }
    }
}

推荐阅读