Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinfile When Condition for env.JOB_NAME

I have a Jenkinsfile I would like to trigger certain steps based on env.JOB_NAME. As a test I have done this;

#!/usr/bin/env groovy
pipeline {
    agent any
     stages {  
      stage('Get ID') {
          when {
              "${env.JOB_NAME}" == 'Notification Sender (dev)'
          }
       steps {
       echo "${env.JOB_NAME}"
      }
    }
  }
}

However I get the error;

WorkflowScript: 6: Expected a when condition @ line 6, column 11.
             when {
             ^

WorkflowScript: 6: Empty when closure, remove the property or add some content. @ line 6, column 11.
             when {
             ^

Can I make the stage run based on the env.JOB_NAME using the when condition?

like image 290
eekfonky Avatar asked Jan 25 '18 09:01

eekfonky


People also ask

How do I ignore failed stage in Jenkins pipeline?

To ignore a failed step in declarative pipeline you basically have two options: Use script step and try-catch block (similar to previous proposition by R_K but in declarative style)

How do you pass a parameter in Jenkins pipeline script?

Using build parameters, we can pass any data we want: git branch name, secret credentials, hostnames and ports, and so on. Any Jenkins job or pipeline can be parameterized. All we need to do is check the box on the General settings tab, “This project is parameterized”: Then we click the Add Parameter button.

How do you skip stage in Jenkins scripted pipeline?

So to mark a stage as skipped you need to call static method markStageSkippedForConditional passing the name of the stage you are skipping. If you're using a version of Jenkins older than mid 2019, you must uncheck Use Groovy Sandbox checkbox, since the Utils method was not yet whitelisted for external use.


1 Answers

Yes, you can.

Try the following

when {
     expression {
         env.JOB_NAME == 'Notification Sender (dev)'
     }
}

There is full documentation on the Pipeline syntax page, but the relevant part is

expression Execute the stage when the specified Groovy expression evaluates to true, for example: when { expression { return params.DEBUG_BUILD } }

like image 176
Dezza Avatar answered Sep 20 '22 10:09

Dezza