Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping a stage in jenkins pipeline without invoking agent?

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 checking 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?

like image 629
Taron Avatar asked Dec 08 '22 17:12

Taron


2 Answers

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.

like image 116
Apurv P. Avatar answered Dec 26 '22 12:12

Apurv P.


I found a solution that worked for me. Although I'm not quite sure why. Introducing a parallel section and using nodes however fixed the issue and the stages are skipped without invoking the agent first. See the modified pipeline:

pipeline {
  agent none 

  options {
   timestamps() 
  }

  environment { 
    //SOME ENV VARS
  }

  stages {
    // more stages
    stage('stage1'){
    when { branch 'master' }
    steps{
      parallel(
        'Job1': {
           node( 'slave1' ){
             //doing stuff
           }
        }
      )
    }
  }
}
like image 45
Taron Avatar answered Dec 26 '22 12:12

Taron