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

This article is part of our Knowledge Base and is provided for guidance-based purposes only. The solutions or workarounds described here are not officially supported by CloudBees and may not be applicable in all environments. Use at your own discretion, and test changes in a safe environment before applying them to production systems.