I've been interested in converting our bespoke Jenkins integrations into a pipeline. However, I can't seem to figure out how to do it.

Can anyone help me with the Jenkins script that could do the following?

    |           |
    |           |
        |       |

1: Start pipeline
10: End pipeline
5: Build some files
   * needed by 6, 7,
   * needed as artifacts at the end
2, 3, 4, 6, 7: Have jUnit result files, should be available at end of
   test (somewhere), even if one failed

Is this even possible? Or should I just join after 3, 4, 5? Like this:

    |       |   |   |
    |---4---|   7---|
    |       |
  • 1
    I'd vote for second option, sounds less likely to break and easier to extend if the need arise. – Tensibai Apr 21 '17 at 9:32
  • 2
    possibly being dense, but i haven't understood what the more complex version adds yet. can you document what "9" does and what it depends on? there is no 8, in case you want to revise and add that. :) – burnettk Apr 23 '17 at 14:41
  • 1
    @BertGoethals You can use Pipeline and still have different jobs. It's possible I'm missing something here. – avi Apr 26 '17 at 12:21
  • 1
    I was trying to do something similar a few days ago. I could get it to work with nested parallel commands, but the flow didn't look right in BlueOcean. – lawnmowerlatte May 4 '17 at 16:13
  • 1
    @BertGoethals Can't you start another pipeline doing 5 and then 6 and 7 from your main pipeline ? – Tensibai May 11 '17 at 12:05

Based on the comments to my question, and some basic testing the following seems to work:

  • Jenkins pipeline just told me: "matrix" or "parallel" cannot be nested inside another "matrix" or "parallel" - So I'm afraid this answer isn't universally valid. – Rick Moritz May 25 '20 at 17:34
  • @RickMoritz As you can see from biniosuaf answer: it’s possible if you move to scripted pipelines. It seems, if you want to remain in the declarative pipeline world, you are stuck without any parallel pipelines. – Vser Dec 4 '20 at 17:44

I had a similar situation in which I wanted to nest other parallel jobs threads inside another parallel one. This code worked for me:

def performDeploymentStages(String node, String app) {
    stage("build") {
        echo "Building the app [${app}] on node [${node}]"
    stage("deploy") {
        echo "Deploying the app ${app}] on node [${node}]"
    stage("test") {
        echo "Testing the app [${app}] on node [${node}]"

pipeline {
    agent {
        label 'master'
    parameters {
        string(name: 'NODES', defaultValue: '1,2,3', description: 'Nodes to build, deploy and test')
        choice(name: 'ENV', choices: 'qa', description: 'Environment')
        string(name: 'APPS', defaultValue: 'app01,app02', description: 'App names')

    stages {
        stage('parallel stage') {
            steps {
                script {
                    def nodes = [:]
                    for (node in params.NODES.tokenize(',')) {
                        def apps = [:]
                        for (app in params.APPS.tokenize(',')) {
                            performDeploymentStages(node, app)
                        parallel apps
                    parallel nodes

To fully benefit from parallel run remember to assign enough executors.

  • Does this snippet work without assigning values to the nodes and apps variables? – jellenberger Feb 8 '19 at 5:17
  • @jellenberger it will not work if these vars will be empty (null/empty string). But it's fine to pass single items (single app, or node) without commas. – biniosuaf Feb 15 '19 at 12:26

Working off of the existing answers and the Jenkins example documentation I came up with the following nested parallel solution. The Stage View (2.19) plugin and Blue Ocean (1.24.5) do not display them as you would hope, so I used the Groovy Postbuild (2.5) plugin (whitelisted) to show a result summary on the build page of the Classic View (the Badge plugin may work as well).

Current environment is using Jenkins LTS 2.277.2, a main "trigger" job, and 4 downstream jobs that build the pieces of my application, all of which are Multibranch pipelines.

I added a method to trigger my downstream Multibranch Pipeline jobs, since they all do the same thing. This is at the end of my Jenkinsfile.

// In case you want to work on the results of the downstream jobs
buildResults = []

// Common code to trigger a downstream job
// Outputs a URL that you can follow in Blue Ocean and Classic View
def performTriggerJob(String jobID) {
    // We need to wrap what we return in a Groovy closure, or else it's invoked
    // when this method is called, not when we pass it to parallel.
    // To do this, you need to wrap the code below in { }, and either return
    // that explicitly, or use { -> } syntax.
    return {
        GIT_BRANCH_FIXUP = env.BRANCH_NAME.replace("/","%2F")
        // propagate: false so we can work after it returns. Try/catch will also work
        res = build( job: "../${jobID}/${GIT_BRANCH_FIXUP}", propagate: false)
        echo "${jobID}: ${res.getResult()} - ${res.buildVariables.get('RUN_DISPLAY_URL')}"
        // Add to buildResults
        buildResults << res

        text = "Downstream Run Result: <a href=\"${res.buildVariables.get('RUN_DISPLAY_URL')}\">${jobID} - ${res.getResult()}</a>"

        if (res.getResult().equals("SUCCESS")) {
        } else {
            error 'JOB FAILED' // this fails the stage

Then in the main pipeline of the main Triggering job, I use script blocks to start the nested parallel jobs.

pipeline {
agent any
stages {
stage('Build Nested parallel') {
   steps {
      script {
         // Runs all these builds in parallel, the 2 nested Jobs
         // have a requirement on the cmake build, but can also run in
         // parallel after that finishes. Declarative cannot nest, but
         // Scripted can.

         // This is a map of 'name': action
         // performTriggerJob returns a Closure which is why this is just a method "call"
         // as Groovy will invoke .call() on parallel 'actions' automatically
         def builds = [
            "subJob1": performTriggerJob('subJob1'),
            "subJob2": performTriggerJob('subJob2'),
            "subJob3": { script {
               // Since we have more work to do than just trigger a job,
               // we have to .call() this Closure directly in the script block to get it to run

               // You can also pass a map directly into the parallel 
               parallel (
                  'nestedJob1': performTriggerJob('nestedJob1'),
                  'nestedJob2': performTriggerJob('nestedJob2')
            } }
         parallel builds
// Other stages

Since performTriggerJob adds the results of the jobs to the variable buildResults we can do something with all the results once everything is done. I copy all artifacts from the last successful build and then zip them up so they're available on the trigger job.

buildResults is a list of (what I believe are) RunWrapper objects, so the methods in this javadoc are what you can call on this object.

// Other stages
stage("Post steps") {
steps {
script {
   for( finishedBuildObj in buildResults ) {
      // Obj to use. Could be this build or the last successful build
      buildObj       = finishedBuildObj
      projectName    = buildObj.getFullProjectName()
      if (buildObj.getResult() != "SUCCESS") {
         buildObj = buildObj.getPreviousSuccessfulBuild()
         projectName: projectName,
         // Allow this build to continue even if no build is found matching the "Which build" condition,
         // the build's workspace does not exist or is inaccessible, or no artifacts are found matching the specified pattern.
         // By default this build step fails the build if no artifacts are copied.
         optional: true,
         // Ignore the directory structure of the artifacts in the source project and copy all matching artifacts directly into the specified target directory.
         // By default the artifacts are copied in the same directory structure as the source project.
         flatten: true,
         // Target base directory for copy, or leave blank to use the workspace.
         // Directory (and parent directories, if any) will be created if needed.
         //May contain references to build parameters like $PARAM.
         target: 'allArtifacts',
         fingerprintArtifacts: true,
         // How to select the build to copy artifacts from, such as latest successful or stable build, or latest "keep forever" build. Other plugins may provide additional selections.
         // The build number of the selected build will be recorded in the environment for later build steps to reference. For details, see the help of "Result variable suffix" in "Advanced" section.
         selector: specific(buildObj.getNumber().toString())
New contributor
KymikoLoco is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.