Operations 3 min read

How to Dynamically Create Jenkins Agent Nodes Using Groovy

This article demonstrates how to programmatically create Jenkins agent nodes on demand with Groovy scripts, covering import statements, node configuration, adding the node to Jenkins, and retrieving node details for further automation in a CI/CD pipeline.

DevOps Cloud Academy
DevOps Cloud Academy
DevOps Cloud Academy
How to Dynamically Create Jenkins Agent Nodes Using Groovy

The article explains a method to dynamically create Jenkins agent nodes for elastic builds, using native Groovy code instead of the Kubernetes plugin.

Import Packages

import hudson.model.Node.Mode
import hudson.slaves.*
import jenkins.model.Jenkins

Add a New Node

String agentName = "zeyang"
String executorNum = "1"
String agentLabel = "JenkinsPod"

agent_node = new DumbSlave(agentName, "Jenkins pod", "/opt/jenkins", executorNum,
               Mode.EXCLUSIVE,
               agentLabel,
               new JNLPLauncher(),
               RetentionStrategy.INSTANCE)
Jenkins.instance.addNode(agent_node)

The parameters are: agentName: node name executorNum: number of executors (as a string) agentLabel: node label description: description text JNLPLauncher(): launch method Mode.EXCLUSIVE: restrict job scheduling to this node RetentionStrategy.INSTANCE: keep the node always online

Retrieve Node Information

node = Jenkins.instance.getNode(agentName)
computer = node.computer
jenkinsUrl = Jenkins.instance.rootUrl.trim().replaceAll('/$', '')

return ""{
"jenkinsUrl" : "${jenkinsUrl}",
"jenkinsHome": "${node.remoteFS.trim()}",
"computerUrl": "${computer.url.trim().replaceAll('/$', '') as String}",
"computerSecret": "${computer.jnlpMac.trim()}"
}""

This script fetches the newly created node's configuration and returns it as a JSON string for downstream processing.

By completing these steps, the first phase of elastic build automation is achieved, and the retrieved node data can later be used to replace pod templates and launch containers in a Kubernetes cluster.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ci/cdDevOpsGroovyJenkinsDynamic Agents
DevOps Cloud Academy
Written by

DevOps Cloud Academy

Exploring industry DevOps practices and technical expertise.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.