217

How can I trigger build of another job from inside the Jenkinsfile?

I assume that this job is another repository under the same github organization, one that already has its own Jenkins file.

I also want to do this only if the branch name is master, as it doesn't make sense to trigger downstream builds of any local branches.

Update:

stage 'test-downstream'
node {
     def job = build job: 'some-downtream-job-name'
}

Still, when executed I get an error

No parameterized job named some-downtream-job-name found

I am sure that this job exists in jenkins and is under the same organization folder as the current one. It is another job that has its own Jenkinsfile.

Please note that this question is specific to the GitHub Organization Plugin which auto-creates and maintains jobs for each repository and branch from your GitHub Organization.

sorin
  • 161,544
  • 178
  • 535
  • 806

5 Answers5

183

In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow

So i used:

stage ('Starting ART job') {
    build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
FrankIJ
  • 1,987
  • 1
  • 10
  • 11
  • 14
    The build job must be embedded in a step (starting with version 0.5) – rhoerbe Sep 01 '17 at 18:19
  • 7
    Is the the BUILD_NUMBER of the Jenkins job invoked by the `build` command returned? How to access the BUILD_NUMBER in one of the following stages? Anyone knows where that command is documented? – user909481 Sep 13 '17 at 15:00
  • 11
    It's `build job: 'freestyle', parameters: [ string(name: 'param1', value:'test_param'), string(name:'dummy', value: "${index}")]` nowadays, from https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel – BartBiczBoży May 15 '19 at 12:46
  • But how to use these parameters passed in 2nd job – Gentle May 31 '19 at 06:51
  • @Gentle. You can access passed paramater as params.systemname – Pankaj Shinde Jun 27 '19 at 10:00
  • API link for `build job`: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/ – Katie Jul 01 '19 at 18:55
  • 6
    Interestingly enough `build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]` did not work for me but: `build job: 'RunArtInTest', parameters: [string(name: 'systemname', value: "${VALUE}")]` worked – Alberto C Apr 02 '20 at 12:07
  • Command syntax changed a little bit. You can generate command from here -->jenkins-home/pipeline-syntax/ there are no need to extra plugins. – rmznbyk 1 Aug 31 '20 at 11:22
170

First of all, it is a waste of an executor slot to wrap the build step in node. Your upstream executor will just be sitting idle for no reason.

Second, from a multibranch project, you can use the environment variable BRANCH_NAME to make logic conditional on the current branch.

Third, the job parameter takes an absolute or relative job name. If you give a name without any path qualification, that would refer to another job in the same folder, which in the case of a multibranch project would mean another branch of the same repository.

Thus what you meant to write is probably

if (env.BRANCH_NAME == 'master') {
    build '../other-repo/master'
}
Jesse Glick
  • 24,539
  • 10
  • 90
  • 112
  • 2
    Thanks! If by any change you also know on how to trigger this build without waiting for it to finish it would be double-awesome :) – sorin Mar 31 '16 at 23:41
  • 64
    Check _Snippet Generator_: `build job: '../other-repo/master', wait: false` – Jesse Glick Apr 02 '16 at 11:29
  • 3
    Is there any way to call the build step with a dynamic branch name? Something like `build job: '../other-repo/$BRANCH_NAME'` where `$BRANCH_NAME` is the Jenkins environment variable pertaining to the branch running the Multibranch project? – msteppe91 Oct 02 '18 at 15:56
  • 4
    if `${BRANCH_NAME}` is available as an environment variable, simple string substitution will do. Just be sure to switch to `"` from `'` for quoting your string. e.g. `build job: "../other-repo/${BRANCH_NAME}"` – Cinderhaze Mar 07 '19 at 21:53
  • 10
    API link for `build job`: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/ – Katie Jul 01 '19 at 18:55
  • How do we check if the second build is complete or fail ? I would like to add a notification if the second build failed !?! – Prathamesh dhanawade Oct 10 '19 at 17:55
  • If anyone wants to know what `build job` returns, then look at this https://javadoc.jenkins.io/plugin/workflow-support/org/jenkinsci/plugins/workflow/support/steps/build/RunWrapper.html So if you do `otherJob = build job ...` then `otherJob.result` will give you the result of that job e.g. `SUCCESS` – Michael Galos Jul 11 '22 at 08:07
82

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }
Katie
  • 45,622
  • 19
  • 93
  • 125
  • 1
    This is fantastic, and the Snippet Generator will actually pull the job for you and provide all the params as fields for you. For me, i wanted to run a new build of the same branch with different params, so it's just `build job: BRANCH_NAME, ...`. I enabled a rudimentary CD flow with this :) – Max Cascone Oct 20 '21 at 20:11
30

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

Flo
  • 491
  • 4
  • 10
  • 3
    I tried adding `build job: 'jobname` but I get this error `No parameterized job named jobname found` and I can assure you that there is a job with this name at the same level in the organization folder. – sorin Mar 30 '16 at 11:33
  • 1
    Yes there is a job, but that job is not parameterized. I am trying to understand how to parameterize a job created by GitHub organization plugin though – yiwen Jun 14 '16 at 23:10
  • 7
    The job name format is: `build job: "${ORGANISATION_NAME}/${REPO_NAME}/master"` – Sahil Ahuja Mar 11 '17 at 09:50
  • 2
    @SahilAhuja That's totally arbitrary and based on your Jenkins layout, and if you want to use an absolute path you need to start with a `/`. Relative paths are fine; sorin's problem was probably that the job calling `build` was a multibranch job, which means a path like `jobname` would try to build the branch `jobname` of the same job; it needs to be `../jobname/branchname` instead – Michael Mrozek Mar 26 '18 at 22:20
  • 1
    This works good but, what happen if the branch specified doesn't exists? – Jaime Alcántara Arnela Sep 25 '18 at 11:12
  • `try { build(job:jobname, wait:false, parameters:params) } catch (Exception ex) { println("Job ${jobname} not triggered: ${ex}") }` – Ed Randall Nov 11 '18 at 08:13
12

Use build job plugin for that task in order to trigger other jobs from jenkins file. You can add variety of logic to your execution such as parallel ,node and agents options and steps for triggering external jobs. I gave some easy-to-read cookbook example for that.

1.example for triggering external job from jenkins file with conditional example:

if (env.BRANCH_NAME == 'master') {
  build job:'exactJobName' , parameters:[
    string(name: 'keyNameOfParam1',value: 'valueOfParam1')
    booleanParam(name: 'keyNameOfParam2',value:'valueOfParam2')
 ]
}

2.example triggering multiple jobs from jenkins file with conditionals example:

 def jobs =[
    'job1Title'{
    if (env.BRANCH_NAME == 'master') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam1',value: 'valueNameOfParam1')
        booleanParam(name: 'keyNameOfParam2',value:'valueNameOfParam2')
     ]
    }
},
    'job2Title'{
    if (env.GIT_COMMIT == 'someCommitHashToPerformAdditionalTest') {
      build job:'exactJobName' , parameters:[
        string(name: 'keyNameOfParam3',value: 'valueOfParam3')
        booleanParam(name: 'keyNameOfParam4',value:'valueNameOfParam4')
        booleanParam(name: 'keyNameOfParam5',value:'valueNameOfParam5')
     ]
    }
}
avivamg
  • 12,197
  • 3
  • 67
  • 61