Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins declarative pipeline expression with boolean environment variable

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 ?

like image 255
fmdaboville Avatar asked Jul 13 '26 03:07

fmdaboville


1 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'
        }
    }
}
like image 81
Sergey Voronezhskiy Avatar answered Jul 16 '26 13:07

Sergey Voronezhskiy