Skipping a stage in jenkins pipeline without invoking agent?

Taron picture Taron · Aug 4, 2017 · Viewed 7.7k times · Source

We use the jenkins pipeline dsl for our job descriptions. Now we have something like that:

pipeline {
  agent none 

  options {
    timestamps() 
  }

  environment { 
    //SOME ENV VARS
  }

  stages {
    // more stages
    stage('stage1'){
    when {
         expression { env.BRANCH_NAME == 'master' }
         }
    agent { label 'slave1' }
    steps{
       //doing stuff
    }
  }
}

A stage in the build process that should only run when the master branch is build, you can think of a deploy job or something in that direction. The problem is, our resources of agents with that particular label are limited. When we build other branches the job still invoke a slave1 agent and than skips the stage after cheking the that the branch is not master. This is bad, because when all slave1 agents are working on master branch jobs, the other jobs will have to wait for a slave1 agent becoming available just to check that it does need to run that stage.

Is there any way with the jenkins pipeline DSL to skip that stage without waiting for the slave1 agent to determine the branch?

Answer

Apurv P. picture Apurv P. · Apr 21, 2018

The approach provided in the accepted answer works because you are not declaring an agent in the stage('stage1'). Instead you explicitly create a node within the steps and so the agent is not created when you check the condition.

This approach will work but it adds unnecessary complexity to your Jenkinsfile. As of Jenkins pipeline plugin version 1.2.6, the correct way to achieve this would be:

pipeline {
  agent none 
  stages {
    // more stages
    stage('stage1'){
      when {
        beforeAgent true
        branch 'master'
      }
      agent { label 'slave1' }
      steps { 
        // do stuff 
      }
    }
  }
}

Check the syntax and available options available in the when tag documentation.