'How to restrict parallel jobs to particular agents in Declarative Pipeline

I have 3 nodes: A, B, C

On each of these nodes I set up a Jenkins agent with its own root directory They all have the following label: test && database && mysql

I want to run a job in parallel on all 3 nodes, to clean the workspace folder on them To achieve that, I wrote this Jenkins script

def labels = "test && mysql && database"

def getNodesName(labels){
    def targets = []
    def nodes = Jenkins.instance.getLabel(labels).getNodes()
    for(node in nodes){
        targets.add(node.getNodeName())
    }
    return targets
}

def nodes = getNodesName(labels)

def cleanWSTasks(targets){
    tasks = [:]
    for(target in targets){
        tasks[target] = {
            node(target){
                script {
                    cleanWs()
                }
            }
        }
    }
    return tasks
}

pipeline{
    agent none
    
    stages{
        
        stage ('Clean Workspace'){
            steps{
                script{
                    parallel cleanWSTasks(nodes)
                }
            }
        }

    }
}

So I thought with node(target) in the cleanWsTasks function I already told Jenkins to restrict the execution of the task only on the particular target node I want. So that all 3 nodes will start cleaning their own workspaces at the same time.

However, what I see is that only 1 node picked up the task to cleanUp the workspace, and it does it 3 times.

For example, it shows:

Running on node A in ...

clean up workspace ..

Running on node A in ...

clean up workspace ..

Running on node A in ...

clean up workspace ..

What did I do wrong in my code? Please help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source