Pom12
Pom12

Reputation: 7880

How to load another groovy script in the same Jenkins node?

When loading a pipeline script from another pipeline script, the two pipelines don't get executed on the same node : the first one is executed on my master node and the second gets executed on a slave node.

I'm using Jenkins pipelines with Pipeline Script from SCM option for a lot of jobs in this way :

E.g. :

node {
    // --- Load the generic pipeline ---
    checkout scm: [$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'http://github/owner/pipeline-repo.git']]]
    load 'common-pipeline.groovy'
}()

My common-pipeline.groovy pipeline does the actual stuff such as building, releasing or deploying artifacts, e.g. :

{ ->
    node() {
        def functions = load 'common/functions.groovy'

        functions.build()
        functions.release()
        functions.deploy()
    }
}

Now I don't want to force the node for each job so both pipelines have node("master") or node("remote") because I really don't want to be handling that manually, however I'd like that once the first pipeline runs on a specific node (either master, slave1, slave2, slave3) the second/loaded pipeline gets executed on the same node, because otherwise my actual Git repository code is not available from other node's workspace...

Is there any way I can specify that I want my second pipeline to be executed on the same node as the first, or maybe pass an argument when using the load step ?

Upvotes: 13

Views: 6896

Answers (2)

GCDev
GCDev

Reputation: 86

How about stashing the workspace after the checkout and before the script load?:

e.g.

stash includes: '**', name: "source"

and then unstash it in another node(){} section:

e.g. unstash "source"

That way it will be available in the other node

Don't forget to clean up the workspace though

Or how about creating a common function that contains the logic for the checkout too (maybe passing in branches as a param). Then you can discard the node(){} in the Jenkins file and just use node(){} entries in your shared groovy script?

e.g. Jenkinsfile

load 'common-pipeline.groovy'
createWorlflow("*/master")

common-pipeline.groovy:

def createWorkflow(branches){
node() {
        def functions = load 'common/functions.groovy'
        functions.checkout(branches)
        functions.build()
        functions.release()
        functions.deploy()
    }
}

Upvotes: 2

JE42
JE42

Reputation: 5149

You can make a parameterized job for the second pipeline and use the parameter to control the node when triggering the second job.

The second pipeline would look like this:

node(runhereParam) {

}

Upvotes: 1

Related Questions