silas / node-jenkins

Jenkins client
https://www.npmjs.com/package/jenkins
MIT License
356 stars 85 forks source link

jenkins.job.build needs parameters to use build auth token #57

Open tmcelhattan opened 6 years ago

tmcelhattan commented 6 years ago

I came across an problem when trying to use jenkins.job.build(options, callback). Under the options section for this it says you can use name (String): job name, parameters (Object, optional): build parameters, or token (String, optional): authorization token.

I was trying to trigger a Jenkins job remotely by selecting the Trigger builds remotely (e.g., from scripts) option in the configuration page of my Jenkins job. The Authentication token I used was 'test'. This was the code I was using to try and trigger that job:

var jenkins = require('jenkins')({ baseUrl: 'http://USERNAME:PASSWORD@YOUR_JENKINS_URL.com', rejectUnauthorized: false });

jenkins.job.build({ name: '<jenkins_job_name>', token: 'test' }, function(err, data) {
  if (err) throw err;

  console.log('queue item number', data);
});

This is error I kept getting in my terminal.

Error: jenkins: job.build: bad request
    at create (/PATH/TO/MY/DIRECTORY/node_modules/papi/lib/errors.js:14:5)
    at Object.response [as Response] (/PATH/TO/MY/DIRECTORY/node_modules/papi/lib/errors.js:38:15)
    at IncomingMessage.<anonymous> (/PATH/TO/MY/DIRECTORY/node_modules/papi/lib/client.js:592:26)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

It turns out that the fix to this problem was that if you are using the Trigger builds remotely (e.g., from scripts) option for your Jenkins job and you set an auth token of your choosing, then you MUST use the parameters option in your code like this:

var jenkins = require('jenkins')({ baseUrl: 'http://USERNAME:PASSWORD@JENKINS_URL.com', rejectUnauthorized: false });

jenkins.job.build({ name: '<jenkins_job_name>', parameters: { token: 'test' } }, function(err, data) {
  if (err) throw err;

  console.log('queue item number', data);
});

After I made that change it immediately worked.

dinukadesilva commented 5 years ago

I assume you can do it by setting header to each request. You can mention them in the initialization.