How to submit Jenkins job via REST API?

15,425

You need to use JSON. See Submitting Jobs.

The following worked for me:

<button 
  type='button'
  onclick='javascript:
    var another_job = function() {
      new Ajax.Request("http://localhost:8081/job/JReport2/build", {
        method: "post",
        parameters: {json: Object.toJSON({parameter: [{name: "foo", value: "fobar"}]})}
    });
  };
  another_job()'>
  Start Job
</button>

What's a bit strange that is works when the button that appears next to the build in the build list is pushed, but does not work with the button that appears on the build description itself.

Share:
15,425
Noel Yap
Author by

Noel Yap

Updated on September 10, 2022

Comments

  • Noel Yap
    Noel Yap almost 2 years

    The following 'Execute system Groovy script' Build Task updates the build's description to add a button that will submit another Jenkins job which is parameterized:

    import hudson.model.Cause
    import hudson.model.Job
    import jenkins.model.Jenkins
    
    final JOB_NAME = 'my-job'
    
    final jenkins = Jenkins.instance
    final job = jenkins.getItemByFullName(JOB_NAME, Job.class)
    final currentBuild = Thread.currentThread().executable
    final buildNumber = currentBuild.getNumber()
    
    job.builds
        .findAll { build -> build.number == buildNumber }
        .each { build ->
            build.setDescription("""
                <button
                    type='button'
                    onclick='javascript:
                        var another_job = function() {
                            parameters = {json: {parameter: [{name: "P4_CHANGELIST", value: "0"}]}};
                            new Ajax.Request("http://builds/job/another-job/build", {
                                method: "post",
                                parameters: Object.toJSON(parameters)
                            });
                        };
                        another_job()'>Continue</button>""")
        }
    

    But upon clicking the Continue button, the request returns a 400 Bad Request. It looks like it's because the build parameters aren't being passed through correctly (if I remove the build parameters from another-job and don't send through parameters, things work fine).

    I'm not sure if the problem is due to bad quoting or the way I'm sending through the build parameters.