5

I wan't to able to script and change number of executors on a node(not master) that already exists. Preferably by using groovy but if there is a plugin or CLI command that could do the trick that is also interesting.

Snippet of what I am trying to do:

jenkins.model.Jenkins.instance.nodes.each { node ->
  println node.getNumExecutors()

  //How do I set the number of executors for a node?
}
ki_
  • 619
  • 1
  • 10
  • 21

4 Answers4

3

I managed it using Slave, which is a subclass of Node.

Below a part of a method I use for that, with target_label and target_executors as parameters

  def nodes = nodesByLabel(target_label)  // requires plugin "Pipeline Utility Steps" 

  def j = Jenkins.getInstanceOrNull();

  for (int i = 0; i < nodes.size(); ++i) {

      def aSlave = (Slave) j.getNode(nodes[i])  // here cast is needed

      aSlave.setNumExecutors(target_executors.toInteger())
      aSlave.save()
      println   aSlave.getDisplayName() + "-" +  aSlave.getNumExecutors()

  }

  j.reload()
YaP
  • 339
  • 3
  • 13
  • Thanks Yap. awesome solution Need to refer below link as well for permission https://stackoverflow.com/questions/38276341/jenkins-ci-pipeline-scripts-not-permitted-to-use-method-groovy-lang-groovyobject – mauryaAjay Apr 03 '22 at 03:26
1

This isn't currently possible — the numExecutors property of a Jenkins node is read-only.

From JENKINS-23534:

[setNumExecutors] is intentionally private since Jenkins does not offer a way to change the number of executors of a SlaveComputer or Slave once created. Instead, you change the configuration, meaning replacing the existing Slave.

Christopher Orr
  • 110,418
  • 27
  • 198
  • 193
1

You could run the script below to modify the Jenkins config.xml file… then just "Reload Configuration from Disk" in Manage Jenkins.

This works from the http://jenkins:8080/script console.

import groovy.xml.XmlUtil 
// the path to your jenkins config.xml
filePath = '/opt/sites/.jenkins/config.xml'
fileContents = new File(filePath).text

def config = new XmlSlurper().parseText(fileContents)

config.slaves[0].slave.each {
  it.numExecutors = 5
}

def writer = new FileWriter(filePath)
XmlUtil.serialize(config, writer)

If you want to reload config automatically you could add:

Jenkins.instance.reload()
Clintm
  • 4,505
  • 3
  • 41
  • 54
0

It's pretty painful that you can't change the number of executors on a slave through the Jenkins API. You'll have to delete the slave and recreate it to change the number of executors, so you'll need to make sure that there are no builds running on the slave first.

Another option to do this in an automated way is to use the create-slave and delete-slave commands in the Jenkins CLI (go to the /cli link in your Jenkins instance for CLI documentation).

gareth_bowles
  • 20,760
  • 5
  • 52
  • 82