Jenkins Declarative Pipeline - dynamically select node (agent) based on git branch

Viewed 3189

I have a Jenkins master and pool of slave nodes which dynamically grows and shrinks (based on load). The master node is called "master" and the slaves have guids for names. Currently none of the nodes have labels.

For my project, I want the "develop" branch from github to build on the master node and pull request branches to build on any one of the slaves. This has been working successfully in a scripted pipeline using node('master') and node('!master').

I would like to start using the new Declarative style of pipeline. Is it currently possible to achieve the same "master" and "not master" behaviour in a Declarative Pipeline, based on the branch name?

In the scripted pipeline, it looks like this:

def selectedNode = BRANCH_NAME == 'develop' ? 'master' : '!master'

node(selectedNode) {
}

Thanks

2 Answers

Answering it in almost 4 years is not actual for the Alex)

But for others it will be.

First of all - set tags to your slaves. It is very useful.

Second - use branch filtering (based on 'when' condition) in declarative pipelines and stage level agents.

pipeline {
  agent none
  stages {
    stage('branch develop') {
      agent { label 'master' }
      when { 
        beforeAgent true
        branch 'develop'
      }
      steps {
        echo 'run build on master node for branch develop'
      }
    }
    stage('branch not develop') {
      agent { label 'another_label' }
      when {
        beforeAgent true 
        not { branch 'develop' }
      }
      steps {
        echo 'run build on other nodes for not develop branch'
      }
    }
  }
}
Related