Alex
Alex

Reputation: 41

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

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

Upvotes: 4

Views: 4027

Answers (2)

Dmitriy Tarasevich
Dmitriy Tarasevich

Reputation: 1242

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'
      }
    }
  }
}

Upvotes: 0

burnettk
burnettk

Reputation: 14037

if it works in scripted, you can generally include the exact same contents within a script step in a declarative pipeline. this runs for me:

pipeline {
  agent { label 'docker' }
  stages {
    stage('build') {
      steps {
        script {
          def selectedNode = BRANCH_NAME == 'develop' ? 'master' : '!master'

          node(selectedNode) {
          }
        }
      }
    }
  }
}

i'd probably go this route rather than futzing with the top-level agent declarations.

Upvotes: 1

Related Questions