Jenkins declarative pipeline expression with boolean environment variable

Viewed 10060

I'm using Jenkins declarative pipeline and I want to make a conditional step depending on an environment variable, which is set according the existence of a file.

So I just want to make something like that : if Dockerfile exist, perform next stage, else don't.

To perform this I tried :

pipeline {
    // ...
    stage {
        stage('Docker') {
            environment {
                IS_DOCKERFILE = fileExists 'Dockerfile'
            }
            when {
                environment name: 'IS_DOCKERFILE', value: true
            }
            stage('Build') {
                // ...
            }
        }
    }
}

Or :

pipeline {
    // ...
    stage {
        stage('Docker') {
            environment {
                IS_DOCKERFILE = fileExists 'Dockerfile'
            }
            when {
                expression {
                    env.IS_DOCKERFILE == true
                }
            }
            stage('Build') {
                // ...
            }
        }
    }
}

In both cases, the Dockerfile exist and it is in the workspace. I also tried with strings ("true") but everytime, the pipeline continue without executing the stage 'Build'.

Any suggestions ?

2 Answers

This is because the exprsssion:

IS_DOCKERFILE = fileExists 'Dockerfile'

Creates the environment variable with boolean value as string:

$ set
IS_DOCKERFILE='false'

So the solution would be to use .toBoolean() like this:

environment {
    IS_DOCKERFILE = fileExists 'Dockerfile'
}
stages {
    stage("build docker image") {
        when {
            expression {
                env.IS_DOCKERFILE.toBoolean()
            }
        }
        steps {
            echo 'fileExists'
        }
    }
    stage("build libraries") {
        when {
            expression {
                !env.IS_DOCKERFILE.toBoolean()
            }
        }
        steps {
            echo 'fileNotExists'
        }
    }
}

As @Sergey already posted, the problem is that you're comparing a string to a boolean. See fileExists: Verify if file exists in workspace.

Besides his answer, you can compare directly to a string:

environment {
    IS_DOCKERFILE = fileExists 'Dockerfile'
}
stages {
    stage("build docker image") {
        when {
            expression {IS_DOCKERFILE == 'true'}
        }
        steps {
            echo 'fileExists'
        }
    }
    stage("build libraries") {
        when {
            expression {IS_DOCKERFILE == 'false'}
        }
        steps {
            echo 'fileNotExists'
        }
    }
}
Related