Prav
Prav

Reputation: 2894

Jenkins pipeline when condition print expression rather than compare

I have to write a pipeline that Builds Terraform infrastructure on Monday and destroy on Friday. I'm trying to determine whether to build or destroy depending on the result of $(date '+%a'), so here's what the condition looks like at the moment:

when {
      beforeAgent true
      expression { 
                 // Using 'Wed' because today is Wednesday
                  return  sh(returnStdout: true, script: '$(date +%a)') == 'Wed'
      }
}

The only problem is every time I ran it, Jenkins shell print the result of sh(returnStdout: true, script: '$(date +%a)') rather than as a comparison value.

[Pipeline] sh
14:52:03 [teardown] Running shell script
14:52:04 + date +%a
14:52:04 + Wed
14:52:04 /jenkins-slave/workspace/teardown@tmp/durable-524bef20/script.sh: 2: /jenkins-slave/workspace/teardown@tmp/durable-524bef20/script.sh: Wed: not found

What am I doing wrong here?

P.S I'm very new to Jenkins like 2 days of use, apologies in advance if I'm being blunt.

Upvotes: 0

Views: 4322

Answers (1)

Baptiste Beauvais
Baptiste Beauvais

Reputation: 2086

As pointed out by @Matt Schuchard in comment your initial problem is the $(date +%a) that make him execute the result of the command date +%a.

But it's entirely resolving your issue as sh(returnStdout: true, script: 'date +%a') will not return you "Wed" for Wednesday but "Wed\n".

Try this :

steps {
    script {
        String v = sh(returnStdout: true, script: 'date +%a')
        print v
        print v.trim()
    }
}

and the output will look like :

enter image description here

So you can either do like in my example and use trim() :

when {
    beforeAgent true
    expression { sh(returnStdout: true, script: 'date +%a').trim() == 'Wed' }
}

Or as Jenkins pipelines are Groovy script you could do it in a Groovy way like :

def week = [1:'Sunday', 2:'Monday', 3:'Tuesday', 4:'Wednesday', 5:'Thursday', 6:'Friday', 7:'Saturday']

pipeline{
    agent any
    stages{
        stage('stage'){
            when {
                beforeAgent true
                expression { week[new Date()[Calendar.DAY_OF_WEEK]] == 'Wednesday' }
            }
...
}

Upvotes: 2

Related Questions