Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

How to compare string variables in Jenkins `when` condition


I'm defining a Jenkins declarative pipeline and having a hard time configuring a step to not execute if two strings are equal.

I've tried several things but string comparison doesn't work.

Here's my current state:

stages {
    stage('Check if image has changed') {
        steps {
            script {
                OLD_DIGEST = sh(returnStdout: true, script: "podman manifest inspect registry/myimage:11 2>/dev/null | jq .config.digest").trim()
                NEW_DIGEST = sh(returnStdout: true, script: "podman inspect --format='sha256:{{.Id}}' myimage:11-tmp").trim()
            }
            sh "echo previous digest:${OLD_DIGEST}, new digest:${NEW_DIGEST}"
        }
    }
    stage('Release') {
        when {
            allOf {
                expression { env.RELEASE != null && env.RELEASE == "true" }
                expression { env.OLD_DIGEST != env.NEW_DIGEST }
            }
        }
        steps {
            sh "echo Releasing image..."
            sh "podman image push myimage:11-tmp registry/myimage:11.${DATE_TIME}"
            sh "podman image push myimage:11-tmp registry/myimage:11"
        }
    }
}

More specifically, the issues lies in the when:

allOf {
    expression { env.RELEASE != null && env.RELEASE == "true" }
    expression { env.OLD_DIGEST != env.NEW_DIGEST }
}

The first expression works fine but I can't make the second work: even if OLD_DIGEST and NEW_DIGEST are different, the step is skipped.

Example output:

previous digest:sha256:736fd651afdffad2ee48a55a3fbab8de85552f183602d5bfedf0e74f90690e32, new digest:sha256:9003077f080f905d9b1a960b7cf933f04756df9560663196b65425beaf21203d
...
Stage "Release" skipped due to when conditional

I've also tried expression { OLD_DIGEST != NEW_DIGEST } (removing the env.) but now the result is the opposite: even when both strings are equals, the step is NOT skipped.

Output in this case:

previous digest:sha256:8d966d43262b818073ea23127dedb61a43963a7fafc5cffdca85141bb4aada57, new digest:sha256:8d966d43262b818073ea23127dedb61a43963a7fafc5cffdca85141bb4aada57
...
Releasing image...

I'm wondering if the issue lies in the expression or allOf at some point.


Solution

  • The root cause of my issue was the output of my two strings to compare which was indeed different: one was "xxx" while the other was xxx but Jenkins output doesn't show the double quotes.


    The correct Jenkins comparison, as stated in the comments, is expression { OLD_DIGEST != NEW_DIGEST } (without env.).