TheWaterProgrammer
TheWaterProgrammer

Reputation: 8219

How to call a Jenkinsfile or a Jenkins Job from another Jenkinsfile?

On a scripted pipeline written in Groovy, I have 2 Jenkinsfiles namely - Jenkinsfile1 and Jenkinsfile2.

Is it possible to call Jenkinsfile2 from Jenkinsfile1.

Lets say following is my Jenkinsfile1

#!groovy

stage('My build') {
    node('my_build_node') {
        def some_output = True
        if (some_output) {
            // How to call Jenkinsfile2 here?
        }
    }
}

How do I call Jenkinsfile2 above when output has a value which is not empty?

Or is it possible to call another Jenkins job which uses Jenkinsfile2?

Upvotes: 0

Views: 3368

Answers (2)

Stefano Martins
Stefano Martins

Reputation: 482

Your question wasn't quite clear to me. If you just want to load and evaluate some piece of Groovy code into yours, you can use load() (as @JoseAO previously stated). Apart from his example, if your file (Jenkinsfile2.groovy) has a call() method, you can use it directly, like this:

node('master') {
    pieceOfCode = load 'Jenkinsfile2.groovy'
    pieceOfCode()
    pieceOfCode.bla()
}

Now, if you want to trigger another job, you can use the build() step, even if you're not using a declarative pipeline. The thing is that the pipeline you're calling must be created in Jenkins, because build() takes as an parameter the job name, not the pipeline filename. Here's an example of how to call a job named pipeline2:

node('master') {
    build 'pipeline2'
}

Now, as for your question "How do I call Jenkinsfile2 above when output has a value which is not empty?", if I understood correctly, you're trying to run some shell command, and if it's empty, you'll load the Jenkinsfile/pipeline. Here's how to achieve that:

// Method #1
node('master') {
    try {
        sh 'my-command-goes-here'
        build 'pipeline2' // if you're trying to call another job
        
        // If you're trying to load and evaluate a piece of code
        pieceOfCode = load 'Jenkinsfile2.groovy'
        pieceOfCode()
        pieceOfCode.bla()       
    }
    catch(Exception e) {
        print("${e}")
    }
}

// Method #2
node('master') {
    def commandResult = sh script: 'my-command-goes-here', returnStdout: true

    if (commandResult.length() != 0) {
        build 'pipeline2' // if you're trying to call another job
        
        // If you're trying to load and evaluate a piece of code
        pieceOfCode = load 'Jenkinsfile2.groovy'
        pieceOfCode()
        pieceOfCode.bla()       
    }
    else {
        print('Something went bad with the command.')
    }
}

Best regards.

Upvotes: 4

JoseAO
JoseAO

Reputation: 1

For example, your Jenkisfile2 it's my "pipeline2.groovy".

    def pipeline2 = load (env.PATH_PIPELINE2 + '/pipeline2.groovy')
    pipeline2.method()

Upvotes: 0

Related Questions