211

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.

5 Answers 5

179

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]]
}
8
  • 14
    The build job must be embedded in a step (starting with version 0.5)
    – rhoerbe
    Sep 1, 2017 at 18:19
  • 6
    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, 2017 at 15:00
  • 11
    It's build job: 'freestyle', parameters: [ string(name: 'param1', value:'test_param'), string(name:'dummy', value: "${index}")] nowadays, from jenkins.io/doc/pipeline/examples/#jobs-in-parallel May 15, 2019 at 12:46
  • But how to use these parameters passed in 2nd job
    – Gentle
    May 31, 2019 at 6:51
  • 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 2, 2020 at 12:07
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'
}
7
  • 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, 2016 at 23:41
  • 63
    Check Snippet Generator: build job: '../other-repo/master', wait: false Apr 2, 2016 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 2, 2018 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 7, 2019 at 21:53
  • 9
    API link for build job: jenkins.io/doc/pipeline/steps/pipeline-build-step
    – Katie
    Jul 1, 2019 at 18:55
76

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
                    }
                }
            }
    }
1
  • 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 :) Oct 20, 2021 at 20:11
29

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

6
  • 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, 2016 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, 2016 at 23:10
  • 7
    The job name format is: build job: "${ORGANISATION_NAME}/${REPO_NAME}/master" Mar 11, 2017 at 9: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 Mar 26, 2018 at 22:20
  • 1
    This works good but, what happen if the branch specified doesn't exists? Sep 25, 2018 at 11:12
10

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')
     ]
    }
}
4
  • But how to receive and use the parameters in 2nd job
    – Gentle
    May 31, 2019 at 7:02
  • 2
    @Gentle. You can access passed paramater as params.systemname Jun 27, 2019 at 10:00
  • is there a possibility for the triggered job to return a return code that indicates whether it was successfully finished or whether it has failed? If yes, please give an example Dec 23, 2020 at 20:33
  • In this example, how can I start “ def jobs”?
    – elulcao
    Jun 5, 2021 at 13:19

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.