Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip a stage in Jenkinsfile pipeline when pipeline name ends with deliver?

I have 2 pipelines one for review and one for deploy. So when the pipeline ends with review, I want to skip Jenkinsfile execution. However, when it ends with deploy, it should execute the stage or the Jenkinsfile.

I tried to use if, but this is a declarative pipeline, so when should be used. I want to avoid execution of stage using when condition if I encounter deploy pipeline end.

#!/usr/bin/env groovy
final boolean Deploy = (env.JOB_NAME as String).endsWith("-deploy")

    
pipeline {
    agent any
    parameters {
        choice(
            choices: ['greeting' , 'silence'],
            description: '',
            name: 'REQUESTED_ACTION')
    }

    stages {
//how to ouse when here to use deploy vairable to avoide execution of stage below
        stage ('Speak') {
            
            steps {
                echo "Hello, bitwiseman!"
            }
        }
    }
}
like image 953
Deepak Raut Avatar asked Oct 09 '18 03:10

Deepak Raut


People also ask

How do I skip a stage in Jenkinsfile?

You can skip stages in declarative pipelines using when , so the following should work. stages { stage('Deploy') { when { equals expected: true, actual: Deploy } steps { // ... } } }

How do you skip 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 skip a pipeline?

to skip pipeline use command: git skipPipeline. normal push with pipeline execution: git push.


2 Answers

You can skip stages in declarative pipelines using when, so the following should work.

stages {
  stage('Deploy') {
    when { equals expected: true, actual: Deploy }
    steps {
      // ...
    }
  }
}
like image 65
StephenKing Avatar answered Sep 23 '22 08:09

StephenKing


An alternative to @StephenKing’s answer, which is also correct, you can rewrite the when block when evaluating Booleans as follows:

stages {
    stage('Deploy') {
        when { 
            expression {
                return Deploy
            }
        }
        steps {
            echo "Hello, bitwiseman!" // Step executes only when Deploy is true

        }
    }
}

This will execute the stage Deploy only when the variable Deploy evaluates to true, else the stage will be skipped.

like image 36
Dibakar Aditya Avatar answered Sep 25 '22 08:09

Dibakar Aditya