Jenkins API Node.js Client
This package, `jenkins-api`, provides a callback-based Node.js client for interacting with Jenkins CI servers. It allows developers to programmatically trigger builds, retrieve build and job information (like console output, build logs, and test results), and manage job configurations (e.g., enable/disable, create/delete jobs). The current stable version is 0.3.1, last published in March 2016. Due to its age and lack of updates, the package is considered abandoned, and it lacks modern features such as Promise-based APIs, async/await support, ESM compatibility, and TypeScript definitions, which are common in contemporary Node.js libraries. Its primary differentiation was a straightforward, direct API mapping for common Jenkins operations at the time of its active development.
Common errors
-
Error: unable to verify the first certificate
cause This error typically occurs when connecting to a Jenkins instance with a self-signed SSL certificate or an untrusted certificate authority, and the Node.js environment does not trust it. The underlying `request` library often defaults to strict SSL verification.fixWhen initializing, pass `strictSSL: false` as an option: `jenkinsapi.init('https://jenkins.yoursite.com', { strictSSL: false });`. Be aware that this disables SSL certificate verification and can expose you to man-in-the-middle attacks. -
Error: Forbidden
cause This indicates an authentication or authorization failure with the Jenkins server. Common causes include incorrect username/password/API token, insufficient user permissions for the requested action, or Jenkins' CSRF protection preventing the request.fixDouble-check the username and API token. Ensure the Jenkins user has the necessary permissions. If CSRF protection is enabled on Jenkins, you might need to disable it (not recommended for production) or use a more modern Jenkins client that can handle crumb tokens. -
ReferenceError: require is not defined in ES module scope
cause This error occurs when trying to use `require()` in a JavaScript file that Node.js interprets as an ES Module (e.g., a `.mjs` file or a `.js` file in a package with `"type": "module"`). The `jenkins-api` package is CommonJS.fixEnsure your file is treated as CommonJS (e.g., use a `.js` extension in a non-module package, or explicitly use `createRequire` from the `module` built-in module for specific imports in ESM contexts if absolutely necessary). The simplest fix is to use CommonJS for files interacting with this library.
Warnings
- breaking The `last_build_report` method is deprecated and explicitly marked as 'OBSOLET' in the README. Use `last_build_info` instead.
- breaking This package is abandoned and has not been updated since March 2016 (version 0.3.1). It is highly unlikely to receive security patches, bug fixes, or new features. Using it in production environments is a significant security risk and could lead to unpatched vulnerabilities.
- gotcha The library exclusively uses a callback-based API, which can lead to 'callback hell' in complex asynchronous flows. It lacks built-in Promise support, making integration with modern `async/await` patterns cumbersome without manual promisification.
- gotcha Authentication to Jenkins often requires handling CSRF protection. Older Jenkins instances or specific configurations might require disabling 'Prevent Cross Site Request Forgery exploits' in Jenkins' global security settings, which is generally not recommended. More modern clients handle 'crumbIssuer' tokens automatically. This library might not inherently support it, leading to 'Forbidden' errors.
- gotcha This package is CommonJS-only and cannot be directly imported using ES Module syntax (`import ... from 'pkg'`). Attempting to do so in an ESM project will result in a runtime error.
Install
-
npm install jenkins-api -
yarn add jenkins-api -
pnpm add jenkins-api
Imports
- jenkinsapi
import jenkinsapi from 'jenkins-api';
const jenkinsapi = require('jenkins-api'); - jenkinsapi.init
const jenkins = new jenkinsapi.init(...);
const jenkins = jenkinsapi.init('http://username:token@jenkins.yourcompany.com'); - jenkins.build
await jenkins.build('your-job-name');jenkins.build('your-job-name', { token: process.env.JENKINS_JOB_TOKEN ?? '' }, (err, data) => { /* handle response */ });
Quickstart
const jenkinsapi = require('jenkins-api');
// Configure with API Token and Jenkins URL
// Replace with your actual Jenkins URL and API token
const jenkinsUrl = process.env.JENKINS_URL || 'http://localhost:8080';
const username = process.env.JENKINS_USERNAME || 'admin';
const apiToken = process.env.JENKINS_API_TOKEN || 'YOUR_API_TOKEN'; // Generate in Jenkins user settings
const jenkins = jenkinsapi.init(`http://${username}:${apiToken}@${jenkinsUrl.replace(/^https?:\/\//, '')}`);
const jobName = 'your-example-job'; // Replace with an actual job name in your Jenkins instance
console.log(`Attempting to get all jobs from ${jenkinsUrl}...`);
jenkins.all_jobs(function(err, data) {
if (err) {
console.error('Error fetching all jobs:', err);
return;
}
console.log('Successfully fetched all jobs:');
data.forEach(job => console.log(`- ${job.name}`));
console.log(`\nAttempting to build job: ${jobName}...`);
// For parameterized builds, use jenkins.build_with_params
jenkins.build(jobName, function(err, data) {
if (err) {
console.error(`Error building job '${jobName}':`, err);
// A common reason for 'forbidden' is CSRF protection. See warnings.
return;
}
console.log(`Successfully triggered build for '${jobName}':`, data);
console.log('Note: Data might be empty for successful build trigger without explicit response from Jenkins.');
});
});