jenkins-client-ts v1.0.1
Jenkins Typescript Client
Typescript API wrapper for working with Jenkins API.
Table of Contents
- Features
- Usage examples
- Installation
- Creating a JenkinsClient
- Common methods parameters
- Types
- Utilities
- License
- API
Features
- Clear extensive API and simple usage
- Types for the majority of Jenkins objects
- Automatic crumb headers issuer with ability to override
- Built-in wait for Jenkins builds and convenient utility waitWhile function to wait for custom conditions
- Exposed requests object to invoke APIs that are not yet implemented
- Ability to retrieve more or less information using
depthandtreeparameters - Ability to override http configurations for calls
Usage Examples
Example 1
Trigger a job build with parameters, wait for it to complete and verify build status.
import { JenkinsBuildResult, JenkinsClient } from 'jenkins-client-ts';
const jenkins = new JenkinsClient({
baseUrl: 'https://localhost:8080',
username: 'admin',
password: '<token> | <password>',
});
(async () => {
const jobPath = '/my-folder/my-job/';
const queueId = await jenkins.jobs.build(jobPath, { param1: 'value1' }, { wait: true });
const buildNumber = (await jenkins.queue.get(queueId)).executable.number;
const build = await jenkins.builds.get(jobPath, buildNumber);
if (build.result === JenkinsBuildResult.SUCCESS) {
console.log('Success!');
}
})();Example 2
Create a job or update configuration if job exists.
import { JenkinsClient } from 'jenkins-client-ts';
const jenkins = new JenkinsClient(...);
(async () => {
const JOB_NAME = 'my-job';
const JOB_CONFIG = `
<flow-definition plugin="workflow-job@2.40">
<actions/>
<description>My Job description</description>
<keepDependencies>false</keepDependencies>
<properties/>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.87">
<script/>
<sandbox>true</sandbox>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>`;
const jobExists = await jenkins.jobs.exists(JOB_NAME);
if (jobExists) {
await jenkins.jobs.setConfig(JOB_NAME, JOB_CONFIG);
} else {
await jenkins.jobs.create('/', JOB_NAME, JOB_CONFIG);
}
})();Example 3
Trigger a job build and stream logs from it to the console.
import { JenkinsClient } from 'jenkins-client-ts';
const jenkins = new JenkinsClient(...);
(async () => {
const jobPath = '/my-folder/my-job/';
const queueId = await jenkins.jobs.build(jobPath, undefined, { waitForStart: true });
const buildNumber = (await jenkins.queue.get(queueId)).executable.number;
const logStream = await jenkins.builds.logStream(jobPath, buildNumber);
logStream.on('data', (text) => {
console.log(text);
});
logStream.on('end', () => {
console.log('Log transfer completed');
});
logStream.on('error', (error) => {
console.log(`There was an error ${error}`);
});
})();Installation
With npm:
npm install jenkins-client-tsWith yarn:
yarn add jenkins-client-tsCreating a JenkinsClient
const jenkins = new JenkinsClient({
baseUrl: 'http://127.0.0.1:8000',
username: 'admin',
password: '<api token | password>',
});JenkinsClientOptions
All fields are optional:
baseUrlstring? - URL of the jenkins controller. Defaulthttp://localhost:8080configAxiosRequestConfig? - http configuration to include in every request such as additional headers or parameters.
Config can also be overridden after client initialization with the config() method
which returns a new instance of the client, leaving initial config untouched.
It allows overriding options only for some calls.
Example 1 - return new client with overridden config
const newClient: JenkinsClient = jenkins.config({ headers: { ['x-custom']: 'cusom-value' } });
const jobs = await newClient.jobs.list('/');Example 2 - or override configuration only for one call
const jobs = await jenkins.config({ params: { depth: 2 } }).jobs.list('/');usernamestring? - username for authentication. If not provided, will use anonymous accesspasswordstring? - API token or real user password. It is preferred to use API token for scripted clients.When real user password is used, Jenkins requires CSRF protection token (crumb) to be sent along with every
POST/DELETErequest. JenkinsClient automatically requests crumb token value.crumbIssuerfunction? - custom function to retrieve Jenkins crumb value. It receives the Jenkinsrequestsobject and expectsPromise<JenkinsCrumbIssuerResponse>as a return value. See example below.
Examples:
const jenkins = new JenkinsClient({
baseUrl: 'http://127.0.0.1:8000',
username: 'admin',
password: '<api token | password>',
// this is the default crumbIssuer function, but you can override it
crumbIssuer: (requests: JenkinsRequests) =>
requests.get('/crumbIssuer/api/json').then(res => ({
crumbRequestField: res.data.crumbRequestField,
crumb: res.data.crumb,
})),
// custom headers to send with every request
config: {
headers: {
'x-custom-header': 'custom-value',
},
},
});Common methods parameters
path parameter
In a number of methods you have to specify a path to Jenkins job or folder, which looks similar to this /job/my-folder/job/my-job
For better readability, you can pass a shorter version of the path: /my-folder/my-job
Exception: if your job name is "job", then you must provide full path, e.g.
/job/my-folder/job/job
Path can also be a full job URL: http://localhost:8080/job/my-folder/job/my-job/
Example
All below variants are equivalent:
await jenkins.jobs.build('/my-folder/my-job');
await jenkins.jobs.build('/job/my-folder/job/my-job');
await jenkins.jobs.build('http://localhost:8080/job/my-folder/job/my-job');// must provide full path or url if job or folder name is "job"
await jenkins.jobs.build('/job/job');
await jenkins.jobs.build('http://localhost:8080/job/job');depth and tree parameters
These parameters allow to control the amount of data returned from the server. Please read about them here.
See below example on how to define depth or tree for calls:
Example - use depth/tree only for one method
const job1 = jenkins.depth(2).jobs.get('my-job');
const job2 = jenkins.tree('name,description').jobs.get('my-job');
const job3 = jenkins.depth(2).tree('name,description,builds[number,result]').jobs.get('my-job');Example - use depth/tree for all methods
// assingn new jenkins client to variable and use it
const jenkinsWithDepthTree = jenkins.depth(2).tree('name,description');
const job1 = jenkinsWithDepthTree.jobs.get('my-job');Types
This client exposes many types for Jenkins objects, such as jobs, builds, credentials, users etc, but not all possible types are presented and some of them defined as any. Do not hesitate to raise issues and ask to add or update types.
Utilities
requests object
JenkinsClient exposes a handy requests object which can be used to invoke APIs that are not yet implemented. It uses provided credentials and automatically requests Jenkins crumb headers, so you only need to worry about actual API call.
Example
const requests = new JenkinsClient().requests;
const result = await requests.get('/some/api/json').then(res => res.data);
await requests.post('/doSomething', { param: 'value' });
await requests.postForm('/doSomething', { param: 'value' });
await requests.postXml('/createSomething', '<xml></xml>');
await requests.delete('/doDeleteSomething');Type guards
Some types are union types, for example JenkinsJob. In order to easily distinguish one type from another this library exposes several type guards for your convenience.
Read more about type guards
Example - job type guards
isWorkflowJob(job)
isWorkflowMultiBranchProject(job)
isFreestyleProject(job)
isFolder(job)
isOrganizationFolder(job)
isMultiConfigurationProject(job)
isMavenProject(job)
isBackupProject(job)
isExternalJob(job)JobPath
Library exposes utility class JobPath to alleviate work with Jenkins job paths.
Example - using JobPath
import { JobPath } from 'jenkins-client-ts';
const jobPath = JobPath.parse('/my-folder/my-job');
console.log(jobPath.path()) // '/job/my-folder/job/my-job/'
console.log(jobPath.prettyPath()) // 'my-folder/my-job'
console.log(jobPath.name()) // 'my-job'
console.log(jobPath.parent()) // JobPath object for /my-folder/waitWhile
Library exposes utility function waitWhile that allows executing a function while specified condition is true. This is useful for situations when you want to wait for build to finish or queue item to be available, etc.
Parameters
func() => Promise\<T> async function that is executed while below condition istrue. Returns data object of generic typeT.condition(res: RequestResult\) => boolean - wait while this function returnstrue.RequestResult<T>has two fieldsokboolean -trueif function did not throw otherwisefalsedataT - function result
options- wait optionsinterval- how frequently to execute function (in milliseconds). Default1000.timeout- what is the maximum time to wait for condition to becomefalse(in milliseconds). Default wait forever.
Example - using waitWhile
import { JenkinsBuild, JenkinsClient, JenkinsQueueItem, waitWhile } from 'jenkins-client-ts';
const jenkins = new JenkinsClient(...);
// Example 1: waiting until queue item with id 123 is available
const queueItem: JenkinsQueueItem | undefined = await waitWhile<JenkinsQueueItem>(
() => jenkins.queue.get(123), // try to get queue with id 123
r => !r.ok, // do it while function throws error (not ok)
{ timeout: 10000, interval: 500 }, // wait for 10 seconds maximum, and retry every 500 milliseconds
)
// Example 2: waiting until build is completed.
// Note that there are special methods for that particular case, this is just an example for waitWhile function usage
const build: JenkinsBuild | undefined = await waitWhile<JenkinsBuild>(
() => jenkins.builds.get('/my-job', 1), // try to get build with number 1
r => !r.data || r.data.building, // do it while build is unavailable or still running
);License
This project is licensed under the Apache 2.0 LICENSE
API
jobs: build get exists list create copy delete setConfig configJson configXml disable enable
builds: get delete wait waitForStart abort log logStream
views: get exists list create setConfig configJson configXml addJob removeJob getRelativePath
users: get exists list create delete whoAmI generateToken revokeToken
nodes: get exists list create copy delete update setConfig configJson configXml markOffline bringOnline
credentials: get exists list create delete setConfig configJson configXml
credentials.domains: get exists list create delete setConfig configJson configXml
Jobs
jenkins.jobs.build
Notes
If parameters are specified will run buildWithParameters otherwise just build. Returns queue item id for the triggered build.
Parameters
pathstring path to the jobparametersRecord<string, string>? parameters for the job.optionsJobBuildOptions? build optionstoken- authentication token used to allow unauthenticated users to run the jobwait- iftruewill wait until job is completedwaitForStart- iftruewill wait for job to start executinginterval- interval in milliseconds to specify how often to check job build status. Default1000. Only ifwaitorwaitForStartflags are enabled.timeout- timeout for job build to complete, will throwTimeout 408error if not completed in time. By default will wait forever. Only ifwaitorwaitForStartflags are enabled.
Returns
Promise[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)
Examples
// trigger a job without parameters
const queueId = await jenkins.jobs.build('/my-folder/my-job/');// trigger a job with parameters
const queueId = await jenkins.jobs.build('job-with-params', { param1: 'value1', param2: 'value2' });// trigger a job with parameters, wait for it to complete, then check wheter job result is 'SUCCESS'
const jobPath = '/my-folder/my-job/';
const queueId = await jenkins.jobs.build(jobPath, { param1: 'value1' }, { wait: true });
const buildNumber = (await jenkins.queue.get(queueId)).executable.number;
const build = await jenkins.builds.get(jobPath, buildNumber);
if (build.result === 'SUCCESS') {
console.log('Success!');
}Code reference
jenkins.jobs.get
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const job = await jenkins.jobs.get('/job/folder/job/my-job');const job = await jenkins.jobs.get('/folder/my-job');{
_class: 'hudson.model.FreeStyleProject',
actions: [
{},
{},
{
_class: 'org.jenkinsci.plugins.displayurlapi.actions.JobDisplayAction',
},
{
_class: 'com.cloudbees.plugins.credentials.ViewCredentialsAction',
},
],
description: '',
displayName: 'freestyle2',
displayNameOrNull: null,
fullDisplayName: 'freestyle2',
fullName: 'freestyle2',
name: 'freestyle2',
url: 'http: * localhost:8080/job/freestyle2/',
buildable: true,
builds: [
{
_class: 'hudson.model.FreeStyleBuild',
number: 2,
url: 'http: * localhost:8080/job/freestyle2/2/',
},
{
_class: 'hudson.model.FreeStyleBuild',
number: 1,
url: 'http: * localhost:8080/job/freestyle2/1/',
},
],
color: 'blue',
firstBuild: {
_class: 'hudson.model.FreeStyleBuild',
number: 1,
url: 'http: * localhost:8080/job/freestyle2/1/',
},
healthReport: [
{
description: 'Build stability: No recent builds failed.',
iconClassName: 'icon-health-80plus',
iconUrl: 'health-80plus.png',
score: 100,
},
],
inQueue: false,
keepDependencies: false,
lastBuild: {
_class: 'hudson.model.FreeStyleBuild',
number: 2,
url: 'http: * localhost:8080/job/freestyle2/2/',
},
lastCompletedBuild: {
_class: 'hudson.model.FreeStyleBuild',
number: 2,
url: 'http: * localhost:8080/job/freestyle2/2/',
},
lastFailedBuild: null,
lastStableBuild: {
_class: 'hudson.model.FreeStyleBuild',
number: 2,
url: 'http: * localhost:8080/job/freestyle2/2/',
},
lastSuccessfulBuild: {
_class: 'hudson.model.FreeStyleBuild',
number: 2,
url: 'http: * localhost:8080/job/freestyle2/2/',
},
lastUnstableBuild: null,
lastUnsuccessfulBuild: null,
nextBuildNumber: 3,
property: [],
queueItem: null,
concurrentBuild: false,
disabled: false,
downstreamProjects: [],
labelExpression: null,
scm: {
_class: 'hudson.scm.NullSCM',
},
upstreamProjects: [
{
_class: 'hudson.model.FreeStyleProject',
name: 'freestyle1',
url: 'http: * localhost:8080/job/freestyle1/',
color: 'blue',
},
],
}Code reference
jenkins.jobs.exists
Parameters
Returns
Promise[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
Examples
const jobExists = await jenkins.jobs.exists('my-job')Code reference
jenkins.jobs.list
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const res = await jenkins.jobs.list('/');[
{
_class: 'com.cloudbees.hudson.plugins.folder.Folder',
name: 'folder',
url: 'http://localhost:8080/job/folder/',
},
{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job1',
url: 'http://localhost:8080/job/job1/',
color: 'notbuilt',
}
]const res = await jenkins.jobs.list('/', true);[
{
_class: 'com.cloudbees.hudson.plugins.folder.Folder',
name: 'folder',
url: 'http://localhost:8080/job/folder/',
},
{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job2',
url: 'http://localhost:8080/job/folder/job/job2',
},
{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job1',
url: 'http://localhost:8080/job/job1/',
color: 'notbuilt',
}
]Code reference
jenkins.jobs.create
Parameters
pathstring path to the folder where to create a jobnamestring new job namexmlConfigstring job xml config
Returns
Examples
await jenkins.jobs.create(
'/',
'my-job',
`
<flow-definition plugin="workflow-job@2.40">
<actions/>
<description>My Job description</description>
<keepDependencies>false</keepDependencies>
<properties/>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.87">
<script/>
<sandbox>true</sandbox>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>`,
);Code reference
jenkins.jobs.copy
Parameters
Returns
Examples
await jenkins.jobs.copy('/folder1/my-job', '/other-folder/job-copy');Code reference
jenkins.jobs.delete
Parameters
Returns
Examples
await jenkins.jobs.delete('/folder/my-job');Code reference
jenkins.jobs.setConfig
Parameters
Returns
Examples
Example:
await jenkins.jobs.setConfig(
'/my-job',
`<flow-definition plugin="workflow-job@1145.v7f2433caa07f">
<actions/>
<description>Job one description</description>
<keepDependencies>false</keepDependencies>
<properties/>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2648.va9433432b33c">
<script>echo "HELLO!"</script>
<sandbox>true</sandbox>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>
`,
);Code reference
src/jobs/jobs.setConfig.ts:45-51
jenkins.jobs.configJson
Parameters
Returns
Examples
const config = await jenkins.jobs.configJson('my-job');{
'flow-definition': {
actions: '',
description: 'My Job description',
keepDependencies: false,
properties: '',
definition: { script: 'echo "hello";', sandbox: true },
triggers: '',
disabled: false,
}
}Code reference
src/jobs/jobs.configJson.ts:45-49
jenkins.jobs.configXml
Parameters
Returns
Promise[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)
Examples
const config = await jenkins.jobs.configXml('my-job');<?xml version="1.0" encoding="UTF-8"?>
<flow-definition plugin="workflow-job@2.40">
<actions/>
<description>My Job description</description>
<keepDependencies>false</keepDependencies>
<properties/>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.87">
<script>echo "hello";</script>
<sandbox>true</sandbox>
</definition>
<triggers/>
<disabled>false</disabled>
</flow-definition>Code reference
src/jobs/jobs.configXml.ts:45-46
jenkins.jobs.disable
Parameters
Returns
Examples
await jenkins.jobs.disable('my-job');Code reference
src/jobs/jobs.disable.ts:29-31
jenkins.jobs.enable
Parameters
Returns
Examples
await jenkins.jobs.enable('my-job');Code reference
Builds
jenkins.builds.get
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const build = await jenkins.builds.get('my-job', 1);{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowRun',
actions: [
{
_class: 'hudson.model.ParametersAction',
parameters: [
{
_class: 'hudson.model.StringParameterValue',
name: 'param',
value: 'MyParam',
},
],
},
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$RemoteCause',
shortDescription: 'Started by remote host 172.26.0.1',
addr: '172.26.0.1',
note: null,
},
],
},
{
_class: 'org.jenkinsci.plugins.workflow.libs.LibrariesAction',
},
{},
{},
{
_class: 'org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction',
},
{
_class:
'org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction',
},
{},
{
_class: 'org.jenkinsci.plugins.workflow.job.views.FlowGraphAction',
},
{},
{},
{},
],
artifacts: [],
building: false,
description: null,
displayName: '#1',
duration: 149,
estimatedDuration: 149,
executor: null,
fullDisplayName: 'a7c06f5c-0234-4d31-b0cc-05b239c6ce21 » jobWParamsAndToken #1',
id: '1',
keepLog: false,
number: 1,
queueId: 1857,
result: 'SUCCESS',
timestamp: 1650317856368,
url: 'http://localhost:8080/job/a7c06f5c-0234-4d31-b0cc-05b239c6ce21/job/jobWParamsAndToken/1/',
changeSets: [],
culprits: [],
nextBuild: null,
previousBuild: null,
}Code reference
src/builds/builds.get.ts:101-106
jenkins.builds.delete
Parameters
Returns
Examples
await jenkins.builds.delete('my-job', 1);Code reference
src/builds/builds.delete.ts:31-37
jenkins.builds.wait
Notes
This function allows usage of depth and tree parameters
Parameters
pathstring path to the jobbuildNumbernumber job build numberoptionsJenkinsBuildWaitOptions build wait optionsinterval- how often to check job build status. Default1000milliseconds.timeout- timeout in milliseconds for job build to complete, will throwTimeout 408error if not completed in time. By default waits forever.
Returns
Examples
const build = await jenkins.builds.wait('/job/folder/job/my-job', 1);{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowRun',
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$UserIdCause',
},
],
},
{
_class: 'org.jenkinsci.plugins.workflow.libs.LibrariesAction',
libraries: [],
},
{
_class: 'org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction',
artifactsUrl: 'http://localhost:8080/job/folder/job/my-job/1/artifact',
changesUrl: 'http://localhost:8080/job/folder/job/my-job/changes',
displayUrl: 'http://localhost:8080/job/folder/job/my-job/1/',
testsUrl: 'http://localhost:8080/job/folder/job/my-job/1/testReport',
},
{
_class:
'org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction',
restartEnabled: false,
restartableStages: [],
},
{},
{
_class: 'org.jenkinsci.plugins.workflow.job.views.FlowGraphAction',
nodes: [
{
_class: 'org.jenkinsci.plugins.workflow.graph.FlowStartNode',
},
{
_class: 'org.jenkinsci.plugins.workflow.cps.nodes.StepAtomNode',
},
{
_class: 'org.jenkinsci.plugins.workflow.graph.FlowEndNode',
},
],
}
],
artifacts: [],
building: false,
description: null,
displayName: '#1',
duration: 142,
estimatedDuration: 142,
executor: null,
fingerprint: [],
fullDisplayName: 'folder » my-job #1',
id: '1',
keepLog: false,
number: 1,
queueId: 1819,
result: 'SUCCESS',
timestamp: 1650054944928,
url: 'http://localhost:8080/job/folder/job/my-job/1/',
changeSets: [],
culprits: [],
nextBuild: null,
previousBuild: null,
}Code reference
src/builds/builds.wait.ts:108-118
jenkins.builds.waitForStart
Notes
This function allows usage of depth and tree parameters
Parameters
pathstring path to the jobbuildNumbernumber job build numberoptionsJenkinsBuildWaitOptions build wait optionsinterval- how often to check job build status. Default1000milliseconds.timeout- timeout in milliseconds for job build to start building, will throwTimeout 408error if not completed in time. By default waits forever.
Returns
Examples
const build = await jenkins.builds.waitForStart('/job/folder/job/my-job', 1);{
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowRun',
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$UserIdCause',
},
],
},
{
_class: 'org.jenkinsci.plugins.workflow.libs.LibrariesAction',
libraries: [],
},
{
_class: 'org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction',
artifactsUrl: 'http://localhost:8080/job/folder/job/my-job/1/artifact',
changesUrl: 'http://localhost:8080/job/folder/job/my-job/changes',
displayUrl: 'http://localhost:8080/job/folder/job/my-job/1/',
testsUrl: 'http://localhost:8080/job/folder/job/my-job/1/testReport',
},
{
_class:
'org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction',
restartEnabled: false,
restartableStages: [],
},
{},
{
_class: 'org.jenkinsci.plugins.workflow.job.views.FlowGraphAction',
nodes: [
{
_class: 'org.jenkinsci.plugins.workflow.graph.FlowStartNode',
},
{
_class: 'org.jenkinsci.plugins.workflow.cps.nodes.StepAtomNode',
},
{
_class: 'org.jenkinsci.plugins.workflow.graph.FlowEndNode',
},
],
}
],
artifacts: [],
building: true,
description: null,
displayName: '#1',
duration: 0,
estimatedDuration: -1,
executor: {
_class: 'hudson.model.OneOffExecutor',
currentExecutable: { _class: 'org.jenkinsci.plugins.workflow.job.WorkflowRun' },
idle: false,
likelyStuck: false,
number: -1,
progress: -1
},
fingerprint: [],
fullDisplayName: 'folder » my-job #1',
id: '1',
keepLog: false,
number: 1,
queueId: 1821,
result: null,
timestamp: 1650054944928,
url: 'http://localhost:8080/job/folder/job/my-job/1/',
changeSets: [],
culprits: [],
nextBuild: null,
previousBuild: null,
}Code reference
src/builds/builds.waitForStart.ts:115-127
jenkins.builds.abort
Notes
https://www.jenkins.io/doc/book/using/aborting-a-build/
Parameters
pathstring path to the jobbuildNumbernumber build numbertypeJenkinsBuildAbortType? the abort action -stop,termorkill. Defaultstop.stop- aborts a pipelineterm- forcibly terminates a build (should only be used if stop does not work)kill- hard kill a pipeline. This is the most destructive way to stop a pipeline and should only be used as a last resort.
Returns
Examples
await jenkins.jobs.abort('/job/my-job', 5);Code reference
src/builds/builds.abort.ts:39-46
jenkins.builds.log
Notes
Returns:
text- log text or html (see options parameter)more- whether the log has more data to return (for example, if build is still running)size- content size. Can be used asstartposition for the next log request.
To return log as a stream while build is still running, use jenkins.builds.logStream
Parameters
pathstring path to the jobbuildNumbernumber job build numberoptionsLogOptions log optionshtml- whether to return log as html or plain text. Defaultfalse.start- return log starting from this position.
Returns
Examples
const log = await jenkins.builds.log('my-job', 1);{
text:
'Started by user admin\r\n' +
'[Pipeline] Start of Pipeline\r\n' +
'[Pipeline] echo\r\n' +
'Hi\r\n' +
'[Pipeline] echo\r\n' +
'Bye!\r\n' +
'[Pipeline] End of Pipeline\r\n' +
'Finished: SUCCESS\r\n',
more: false,
size: 1535,
}Code reference
src/builds/builds.log.ts:60-74
jenkins.builds.logStream
Parameters
pathstring path to the jobbuildNumbernumber job build numberoptionsLogStreamOptions optionsinterval- how frequently return log chunks. Default every1000milliseconds.start- return log starting from this position. Default0.
Returns
LogReadableStream
Examples
const logStream = await jenkins.builds.logStream('my-job', 1);
logStream.pipe(process.stdout)const logStream = await jenkins.builds.logStream('my-job', 1, { interval: 500 });
logStream.on('data', (text) => {
console.log(text);
});
logStream.on('end', () => {
console.log('Log transfer completed');
});
logStream.on('error', (error) => {
console.log(`There was an error ${error}`);
});Code reference
src/builds/builds.logStream.ts:109-114
Queue
jenkins.queue.get
Notes
This function allows usage of depth and tree parameters
Parameters
idnumber queue id
Returns
Examples
const queueItem = await jenkins.queue.get(1790);{
_class: 'hudson.model.Queue$WaitingItem',
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$UserIdCause',
shortDescription: 'Started by user admin',
userId: 'admin',
userName: 'admin',
},
],
},
],
blocked: false,
buildable: false,
id: 1790,
inQueueSince: 1650047426432,
params: '',
stuck: false,
task: {
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job1',
url: 'http://localhost:8080/job/e010173e-ce32-441f-a9a7-e1d2ecd4fbc2/job/job1/',
color: 'notbuilt',
},
url: 'queue/item/1790/',
why: 'In the quiet period. Expires in 4.6 sec',
timestamp: 1650047431432,
}Code reference
jenkins.queue.list
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const queue = await jenkins.queue.list();const queue = await jenkins.queue.list('/folder/my-job');{
_class: 'hudson.model.Queue',
discoverableItems: [],
items: [
{
_class: 'hudson.model.Queue$WaitingItem',
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$UserIdCause',
shortDescription: 'Started by user admin',
userId: 'admin',
userName: 'admin',
},
],
},
],
blocked: false,
buildable: false,
id: 1798,
inQueueSince: 1650047730909,
params: '',
stuck: false,
task: {
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job1',
url: 'http://localhost:8080/job/e0c9a9bd-5577-4670-bc6f-ee40abcd2adc/job/job1/',
color: 'notbuilt',
},
url: 'queue/item/1798/',
why: 'In the quiet period. Expires in 4.8 sec',
timestamp: 1650047735909,
},
{
_class: 'hudson.model.Queue$WaitingItem',
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'hudson.model.Cause$UserIdCause',
shortDescription: 'Started by user admin',
userId: 'admin',
userName: 'admin',
},
],
},
],
blocked: false,
buildable: false,
id: 1799,
inQueueSince: 1650047730984,
params: '',
stuck: false,
task: {
_class: 'org.jenkinsci.plugins.workflow.job.WorkflowJob',
name: 'job2',
url: 'http://localhost:8080/job/e0c9a9bd-5577-4670-bc6f-ee40abcd2adc/job/job2/',
color: 'notbuilt',
},
url: 'queue/item/1799/',
why: 'In the quiet period. Expires in 4.9 sec',
timestamp: 1650047735984,
},
],
}Code reference
src/queue/queue.list.ts:107-114
jenkins.queue.cancel
Parameters
idnumber queue item id
Returns
Examples
await jenkins.queue.cancel(1701);Code reference
src/queue/queue.cancel.ts:28-30
Views
jenkins.views.get
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const rootView = await jenkins.views.get('/', 'All');{
_class: 'hudson.model.AllView',
description: null,
jobs: [
{
_class: 'com.cloudbees.hudson.plugins.folder.Folder',
name: 'my-folder',
url: 'http://localhost:8080/job/my-folder/',
},
],
name: 'all',
property: [],
url: 'http://localhost:8080/',
}Code reference
jenkins.views.exists
Parameters
Returns
Promise[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
Examples
const viewExists = await jenkins.views.exists('/', 'All')Code reference
src/views/views.exists.ts:30-34
jenkins.views.list
Notes
This function allows usage of depth and tree parameters
Parameters
Returns
Examples
const views = await jenkins.views.list('/');[
{
_class: 'hudson.model.AllView',
name: 'all',
url: 'http://localhost:8080/',
}
]Code reference
jenkins.views.create
Parameters
pathstring path to the folder with viewnamestring new view namemodestring view mode -ListVieworMyView
Returns
Examples
await jenkins.views.create('/', 'ViewName', 'ListView');Code reference
src/views/views.create.ts:31-42
jenkins.views.setConfig
Parameters
pathstring path to the folder with viewnamestring view namexmlConfigstring xml configuration for the view
Returns
Examples
await jenkins.views.setConfig(
'/',
'MyView',
`
<hudson.model.ListView>
<name>MyView</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
<jobNames>
<comparator class="hudson.util.CaseInsensitiveComparator"/>
</jobNames>
<jobFilters/>
<columns>
<hudson.views.StatusColumn/>
<hudson.views.WeatherColumn/>
<hudson.views.JobColumn/>
<hudson.views.LastSuccessColumn/>
<hudson.views.LastFailureColumn/>
<hudson.views.LastDurationColumn/>
<hudson.views.BuildButtonColumn/>
</columns>
<recurse>false</recurse>
</hudson.model.ListView>`,
);Code reference
src/views/views.setConfig.ts:55-62
jenkins.views.configJson
Parameters
Returns
Examples
const config = await jenkins.views.configJson('/', 'MyView');{
'hudson.model.ListView': {
name: 'MyView',
filterExecutors: false,
filterQueue: false,
properties: '',
jobNames: { comparator: '' },
jobFilters: '',
columns: {
'hudson.views.StatusColumn': '',
'hudson.views.WeatherColumn': '',
'hudson.views.JobColumn': '',
'hudson.views.LastSuccessColumn': '',
'hudson.views.LastFailureColumn': '',
'hudson.views.LastDurationColumn': '',
'hudson.views.BuildButtonColumn': '',
},
recurse: false,
}
}Code reference
src/views/views.configJson.ts:53-61
jenkins.views.configXml
Parameters
Returns
Examples
const configXml = await jenkins.views.configXml('/', 'MyView');<?xml version="1.1" encoding="UTF-8"?>
<hudson.model.ListView>
<name>MyView</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
<jobNames>
<comparator class="hudson.util.CaseInsensitiveComparator"/>
</jobNames>
<jobFilters/>
<columns>
<hudson.views.StatusColumn/>
<hudson.views.WeatherColumn/>
<hudson.views.JobColumn/>
<hudson.views.LastSuccessColumn/>
<hudson.views.LastFailureColumn/>
<hudson.views.LastDurationColumn/>
<hudson.views.BuildButtonColumn/>
</columns>
<recurse>true</recurse>
</hudson.model.ListView>Code reference
src/views/views.configXml.ts:54-58
jenkins.views.addJob
Notes
If view configuration has enabled Job Filter "Recurse in subfolders" then you can add any job located in the subfolders but if this filter is disabled, you can only add jobs located directly in the current folder.
Parameters
pathstring path to the folder with viewnamestring view namejobPathstring path for the job to add. Path can be relative to the folder or absolute. If job is not located in the folder it won't be added.
Returns
Examples
await jenkins.views.addJob('/my-folder', 'MyView', '/my-folder/my-job');await jenkins.views.addJob('/my-folder', 'MyView', 'my-job');Code reference
src/views/views.addJob.ts:40-49
jenkins.views.removeJob
Parameters
pathstring path to the folder with viewnamestring view name to deletejobPathstring path for the job to remove. Path can be relative to the folder or absolute.
Returns
Examples
await jenkins.views.removeJob('/my-folder', 'MyView', 'my-job');await jenkins.views.removeJob('/my-folder', 'MyView', '/my-folder/my-job');Code reference
src/views/views.removeJob.ts:37-46
jenkins.views.getRelativePath
Notes
Since views can be nested within folders and user may provide the full path to the job we need to transform the provided path to the path relative to the folder where the view is created.
Parameters
Returns string
deleteView
src/views/views.delete.ts:30-36
Delete view
Parameters
Returns
Examples
await jenkins.views.delete('/', 'MyView');Code reference
src/views/views.getRelativePath.ts:23-30
Users
jenkins.users.get
Notes
This function allows usage of depth and tree parameters
Parameters
namestring user name
Returns
Examples
const user = await jenkins.users.get('john');{
_class: 'hudson.model.User',
absoluteUrl: 'http://localhost:8080/user/john',
description: null,
fullName: 'john.doe',
id: 'john',
property: [
{ _class: 'jenkins.security.ApiTokenProperty' },
{
_class: 'com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty',
},
{
_class: 'hudson.plugins.emailext.watching.EmailExtWatchAction$UserProperty',
triggers: [],
},