Pipeline with conditional stages based on a file existing on the filesystem

Article ID:360027607532
1 minute readKnowledge base

Issue

I would like to have a Jenkins Pipeline that will conditionally run specific stages depending if a file exists on the filesystem.

Resolution

Generally this use case may not a best practise, as relying on files on a filesystem can sometimes mean you have files that are outside of source control, but there are some situations where this is valid.

pipeline{
    agent any
    environment{
        MY_FILE = fileExists '/tmp/myfile'
    }
    stages{
        stage('conditional if exists'){
            when { expression { MY_FILE == 'true' } }
            steps {
                echo "file exists"
            }
        }
        stage('conditional if not exists'){
            when { expression { MY_FILE == 'false' } }
            steps {
                echo "file does not exist"
            }
        }
    }
}

Tested product/plugin versions