Jenkins Shared Library

601 views
Skip to first unread message

Raviraj Bhatane

unread,
Jul 13, 2021, 4:49:57 PM7/13/21
to Jenkins Users
I have a question regarding the execution of JSL scripts on the Jenkins Agent node. I noticed JSL scripts get executed only on Jenkins Master, is it possible to run the JSL script on Jenkins Agents?

I have multiple stages in my Pipeline and I wish to run those stages on different Jenkins Agent nodes. 

My primary motivation for using JSL is end-to-end Pipeline testability during development using “replay”, where I can modify Jenkinsfile as well as scripts from JSL.

This is a snippet of my Pipeline --

pipeline {
   agent { label 'scdc-generic-w10x64' }
   options {
      timestamps()
   }
   stages {
      stage('Log ip') {
        steps {
            script {
               bat "ipconfig -all"   // *** Gets executed on Jenkins Agent ***
               foo = jsl.foo.new(this) // foo is a Groovy class in JSL
               foo.logIpAddress()   // *** Gets executed on Jenkins Master ***
            }
         }
      }
   }
   post {
      always {
         cleanWs()
      }
   }
}

Ivan Fernandez Calvo

unread,
Jul 14, 2021, 2:15:38 PM7/14/21
to Jenkins Users
no, it is not possible, the groovy code is executed in the Jenkins controller by design, it is designed to execute simple logic of orchestration logic, if you want to execute heavy logic you should do it on the agents by using steps that run scripts or processes on the agent. 

pipeline {
   agent { label 'scdc-generic-w10x64' }
   options {
      timestamps()
   }
   stages {
      stage('Log ip') {
        steps {
            script {
               bat "ipconfig -all"   // *** Gets executed on Jenkins Agent ***
               def stdout = bat(returnStdout: true, script: "groovy my-script.groovy" // *** Gets executed on Jenkins Agent ***
               echo "stdout"
            }
         }
      }
   }
   post {
      always {
         cleanWs()
      }
   }
}

the script can be whatever you want groovy, python, PowerShell, or a simple binary, the only that you have to have is the script interpreter installed in your Jenkins agent 
take a look at this fantastic Jesse Glick presentation to know why https://www.youtube.com/watch?v=Zeqc6--0eQw

Ivan Fernandez Calvo

unread,
Jul 14, 2021, 2:21:25 PM7/14/21
to Jenkins Users
one more thing if you want to have those scripts shared across pipelines you can use the shared library.
You can define those scripts as resources in the shared library and invoke them directly

def stdout = bat(returnStdout: true, script: "groovy -e '${libraryResource('my-script.groovy'))}' ")

Raviraj Bhatane

unread,
Jul 15, 2021, 6:13:45 PM7/15/21
to Jenkins Users
That's great! Thanks, Ivan!

I kept my scripts in JSL's resource folder and loading them on the Agent using "libraryResource".   
Reply all
Reply to author
Forward
0 new messages