Skip to content

Instantly share code, notes, and snippets.

@taherbs
Last active July 17, 2023 15:08
Show Gist options
  • Save taherbs/40ee592707f023005a02f196e71defa2 to your computer and use it in GitHub Desktop.
Save taherbs/40ee592707f023005a02f196e71defa2 to your computer and use it in GitHub Desktop.
This script defines a Jenkins pipeline that executes tasks in parallel on multiple nodes based on specified labels, retrieves the operating system of each node, and allows selection of nodes using regular expressions.
/*
This script defines a Jenkins pipeline that executes tasks in parallel on multiple nodes based on specified label expression,
retrieves the operating system of each node, and allows selection of nodes using regular expressions.
*/
properties([
parameters([
[$class: 'LabelParameterDefinition',
allNodesMatchingLabel: true,
name: 'NODE_LABELS',
defaultValue: 'Unity',
description: 'You can use regular expressions, for example: "windows && unity", "windows || mac"',
nodeEligibility: [$class: 'AllNodeEligibility'],
triggerIfResult: 'allCases'
]
])
])
pipeline {
// I prefer to have a dedicated node to execute admin tasks
agent none
stages {
stage('agents-tasks') {
steps {
script {
def execOnNode = { agentName ->
node("${agentName}") {
stage("${agentName}") {
println(env.NODE_NAME)
println(getNodeOs())
}
}
}
buildParallelOnNodes(NODE_LABELS, execOnNode)
}
}
}
}
}
def getNodesByLabelExpression(String labelExpression) {
def label = Jenkins.instance.getLabel(labelExpression)
def nodes = label.getNodes()
if (!(nodes)) {
throw new RuntimeException("Could not find any node matching label expression: '${labelExpression}'!")
}
def agents = []
for (node in nodes) {
agents.add(node.getNodeName())
}
return agents
}
def buildParallelOnNodes(String labelExpression, Closure execOnNode) {
def buildOnNodeList = [:]
// Get node list with the specified labelExpression
def nodeList = getNodesByLabelExpression(labelExpression)
println("Node list with label Expression ${labelExpression}: ${nodeList}")
for(i=0; i<nodeList.size(); i++) {
def agentName = nodeList[i]
// skip the null entries in the nodeList
if (agentName != null) {
println "Prearing task on: " + agentName
buildOnNodeList["node_" + agentName] = { execOnNode(agentName) }
}
}
parallel buildOnNodeList
}
def getNodeOs() {
def nodeOs = Jenkins.instance.getNode(env.NODE_NAME).toComputer().getSystemProperties().get('os.name')
return nodeOs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment