Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Jenkins execute code on remote slaves?

I have a piece of code to list all files in the /tmp directory on two nodes, like so (scripted syntax):

stage('Demo') {
    node('node1') {
        println new File('/tmp/').listFiles().toList()
    }

    node('node2') {
        println new File('/tmp/').listFiles().toList()
    }
}

However, the results from both nodes are identical. It looks like the code is executed on the master, only the println function is executed on the 2 nodes.

The question is: is it true? and if so, how do I know if the code is executed on master or slaves?

like image 264
FuzzY Avatar asked Sep 15 '25 19:09

FuzzY


2 Answers

All Jenkins steps that use the node context will execute on those agents (from the node blocks). For example, a sh 'ls -1 /tmp/' would run the ls -1 /tmp/ command on that agent that is in the block. But, the actual Groovy sh method and JVM code execute on the Jenkins master.

All of the Groovy inside of a Jenkins pipeline is executed on the master in a special source-transformed fashion from the Pipeline Groovy Plugin. Hence, why new File('/tmp') executes on the master rather than the agent. If you were running your pipeline using the security sandbox, you would get a security exception because new File by default is disallowed. In fact, any of the normal JVM style methods are disallowed. For example, wouldn't it be terrible if a pipeline could call System.exit(0) and shut down Jenkins for all of the users?

Similar questions:

  • Calling shell commands in groovy script, used in Jenkins pipeline
  • Why build executor status showing two jobs for one pipeline job?
like image 106
mkobit Avatar answered Sep 18 '25 10:09

mkobit


Pipeline DSL context runs on master node even that your write node('someAgentName') in your pipeline. new File will work only on master.

But you can read data from file via sh(). Something like:

def list = sh(returnStdout: true, script: 'ls').trim()
like image 28
FCh Avatar answered Sep 18 '25 09:09

FCh