How do I use `when` condition on a file's last modified time in Jenkins pipeline syntax

Viewed 1235

I am creating a Jenkins pipeline, I want certain stage to be triggered only when a particular log file's(log file is located in the server node where all the stages are going to run) last modified date is updated after the initiation of pipeline job, I understand we need to use "When" condition but not really sure how to implement it.

Tried referring some of the pipeline related portals but could not able to find an answer

Can some please help me through this?

Thanks in advance!

1 Answers

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"
            }
        }
    }
}
Related