npm.io
1.0.1 • Published 4 years ago

jenkins-client-ts

Licence
Apache-2.0
Version
1.0.1
Deps
5
Size
471 kB
Vulns
27
Weekly
0
Stars
7

Jenkins Typescript Client

Run Tests codecov

Typescript API wrapper for working with Jenkins API.

Table of Contents

Features

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-ts

With yarn:

yarn add jenkins-client-ts

Creating a JenkinsClient

const jenkins = new JenkinsClient({
  baseUrl: 'http://127.0.0.1:8000',
  username: 'admin',
  password: '<api token | password>',
});
JenkinsClientOptions

All fields are optional:

  • baseUrl string? - URL of the jenkins controller. Default http://localhost:8080
  • config AxiosRequestConfig? - http configuration to include in every request such as additional headers or parameters.
Another way to provide config overrides

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('/');

Credentials:

  • username string? - username for authentication. If not provided, will use anonymous access

  • password string? - 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/DELETE request. JenkinsClient automatically requests crumb token value.

  • crumbIssuer function? - custom function to retrieve Jenkins crumb value. It receives the Jenkins requests object and expects Promise<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 is true. Returns data object of generic type T.
  • condition (res: RequestResult<T>) => boolean - wait while this function returns true. RequestResult<T> has two fields
    • ok boolean - true if function did not throw otherwise false
    • data T - function result
  • options - wait options
    • interval - how frequently to execute function (in milliseconds). Default 1000.
    • timeout - what is the maximum time to wait for condition to become false (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

queue: get list cancel

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

labels: get

plugins: list

credentials: get exists list create delete setConfig configJson configXml

credentials.domains: get exists list create delete setConfig configJson configXml

Jobs

jenkins.jobs.build
Trigger a job build
Notes

If parameters are specified will run buildWithParameters otherwise just build. Returns queue item id for the triggered build.

Parameters
  • path string path to the job

  • parameters Record<string, string>? parameters for the job.

  • options JobBuildOptions? build options

    • token - authentication token used to allow unauthenticated users to run the job
    • wait - if true will wait until job is completed
    • waitForStart - if true will wait for job to start executing
    • interval - interval in milliseconds to specify how often to check job build status. Default 1000. Only if wait or waitForStart flags are enabled.
    • timeout - timeout for job build to complete, will throw Timeout 408 error if not completed in time. By default will wait forever. Only if wait or waitForStart flags are enabled.
Returns

Promise<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

src/jobs/jobs.build.ts:75-116

jenkins.jobs.get
Get job information
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsJob>

Examples
const job = await jenkins.jobs.get('/job/folder/job/my-job');
const job = await jenkins.jobs.get('/folder/my-job');
Example result
{
  _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

src/jobs/jobs.get.ts:130-131

jenkins.jobs.exists
Check whether the specified job exists
Parameters
Returns

Promise<boolean>

Examples
const jobExists = await jenkins.jobs.exists('my-job')
Code reference

src/jobs/jobs.exists.ts:30-31

jenkins.jobs.list
List jobs
Notes

This function allows usage of depth and tree parameters

Parameters
  • path string path to the folder
  • recursive boolean? whether to list jobs in the subfolders recursively
Returns

Promise<Array<JenkinsJob>>

Examples
const res = await jenkins.jobs.list('/');
Example result
[
  {
    _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);
Example result
[
  {
    _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

src/jobs/jobs.list.ts:76-106

jenkins.jobs.create
Create job or folder from xml config
Parameters
  • path string path to the folder where to create a job
  • name string new job name
  • xmlConfig string job xml config
Returns

Promise<void>

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

src/jobs/jobs.create.ts:48-55

jenkins.jobs.copy
Copy job from one path to another
Parameters
  • fromPath string path to the source job
  • toPath string path to the new job
Returns

Promise<void>

Examples
await jenkins.jobs.copy('/folder1/my-job', '/other-folder/job-copy');
Code reference

src/jobs/jobs.copy.ts:33-41

jenkins.jobs.delete
Delete job or folder
Parameters
Returns

Promise<void>

Examples
await jenkins.jobs.delete('/folder/my-job');
Code reference

src/jobs/jobs.delete.ts:29-31

jenkins.jobs.setConfig
Update job with xml configuration
Parameters
Returns

Promise<void>

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
Get job configuration as json object
Parameters
Returns

Promise<any>

Examples
const config = await jenkins.jobs.configJson('my-job');
Example result
{
  '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
Get job configuration as xml string
Parameters
Returns

Promise<string>

Examples
const config = await jenkins.jobs.configXml('my-job');
Example result
<?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
Disable job
Parameters
Returns

Promise<void>

Examples
await jenkins.jobs.disable('my-job');
Code reference

src/jobs/jobs.disable.ts:29-31

jenkins.jobs.enable
Enable job
Parameters
Returns

Promise<void>

Examples
await jenkins.jobs.enable('my-job');
Code reference

src/jobs/jobs.enable.ts:29-31

Builds

jenkins.builds.get
Get build information
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsBuild>

Examples
const build = await jenkins.builds.get('my-job', 1);
Example result
{
  _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
Delete build
Parameters
Returns

Promise<void>

Examples
await jenkins.builds.delete('my-job', 1);
Code reference

src/builds/builds.delete.ts:31-37

jenkins.builds.wait
Wait for build to complete and return build information
Notes

This function allows usage of depth and tree parameters

Parameters
  • path string path to the job

  • buildNumber number job build number

  • options JenkinsBuildWaitOptions build wait options

    • interval - how often to check job build status. Default 1000 milliseconds.
    • timeout - timeout in milliseconds for job build to complete, will throw Timeout 408 error if not completed in time. By default waits forever.
Returns

Promise<JenkinsBuild>

Examples
const build = await jenkins.builds.wait('/job/folder/job/my-job', 1);
Example result
{
  _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
Wait for build to start and return build information
Notes

This function allows usage of depth and tree parameters

Parameters
  • path string path to the job

  • buildNumber number job build number

  • options JenkinsBuildWaitOptions build wait options

    • interval - how often to check job build status. Default 1000 milliseconds.
    • timeout - timeout in milliseconds for job build to start building, will throw Timeout 408 error if not completed in time. By default waits forever.
Returns

Promise<JenkinsBuild>

Examples
const build = await jenkins.builds.waitForStart('/job/folder/job/my-job', 1);
Example result
{
  _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
Abort the build
Notes

https://www.jenkins.io/doc/book/using/aborting-a-build/

Parameters
  • path string path to the job

  • buildNumber number build number

  • type JenkinsBuildAbortType? the abort action - stop, term or kill. Default stop.

    • stop - aborts a pipeline
    • term - 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

Promise<void>

Examples
await jenkins.jobs.abort('/job/my-job', 5);
Code reference

src/builds/builds.abort.ts:39-46

jenkins.builds.log
Return build 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 as start position for the next log request.

To return log as a stream while build is still running, use jenkins.builds.logStream

Parameters
  • path string path to the job

  • buildNumber number job build number

  • options LogOptions log options

    • html - whether to return log as html or plain text. Default false.
    • start - return log starting from this position.
Returns

Promise<JenkinsLog>

Examples
const log = await jenkins.builds.log('my-job', 1);
Example result
{
  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
Return build log stream
Parameters
  • path string path to the job

  • buildNumber number job build number

  • options LogStreamOptions options

    • interval - how frequently return log chunks. Default every 1000 milliseconds.
    • start - return log starting from this position. Default 0.
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
Get queue item by id
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsQueueItem>

Examples
const queueItem = await jenkins.queue.get(1790);
Example result
{
  _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

src/queue/queue.get.ts:65-66

jenkins.queue.list
List queue
Notes

This function allows usage of depth and tree parameters

Parameters
  • path string? optionally specify job path to filter queue items by job
Returns

Promise<JenkinsQueue>

Examples
const queue = await jenkins.queue.list();
const queue = await jenkins.queue.list('/folder/my-job');
Example result
{
  _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
Cancel queue item by id
Parameters
Returns

Promise<void>

Examples
await jenkins.queue.cancel(1701);
Code reference

src/queue/queue.cancel.ts:28-30

Views

jenkins.views.get
Get view info
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsView>

Examples
const rootView  = await jenkins.views.get('/', 'All');
Example result
{
  _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

src/views/views.get.ts:51-55

jenkins.views.exists
Check whether view exists
Parameters
Returns

Promise<boolean>

Examples
const viewExists = await jenkins.views.exists('/', 'All')
Code reference

src/views/views.exists.ts:30-34

jenkins.views.list
List views
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<Array<JenkinsView>>

Examples
const views = await jenkins.views.list('/');
Example result
[
  {
    _class: 'hudson.model.AllView',
    name: 'all',
    url: 'http://localhost:8080/',
  }
]
Code reference

src/views/views.list.ts:43-50

jenkins.views.create
Create view
Parameters
  • path string path to the folder with view
  • name string new view name
  • mode string view mode - ListView or MyView
Returns

Promise<void>

Examples
await jenkins.views.create('/', 'ViewName', 'ListView');
Code reference

src/views/views.create.ts:31-42

jenkins.views.setConfig
Update view configuration with xml config
Parameters
  • path string path to the folder with view
  • name string view name
  • xmlConfig string xml configuration for the view
Returns

Promise<void>

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
Get view configuration as json object
Parameters
Returns

Promise<any>

Examples
const config = await jenkins.views.configJson('/', 'MyView');
Example result
{
  '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
Get view configuration as xml string
Parameters
Returns

Promise<any>

Examples
const configXml = await jenkins.views.configXml('/', 'MyView');
Example result
<?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
Add job to the view
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
  • path string path to the folder with view
  • name string view name
  • jobPath string 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

Promise<void>

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
Remove job from view
Parameters
  • path string path to the folder with view
  • name string view name to delete
  • jobPath string path for the job to remove. Path can be relative to the folder or absolute.
Returns

Promise<void>

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
This helper function only applies to the addJob and removeJob for views.
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
  • path string path to the folder with view
  • name string view name to delete
Returns

Promise<void>

Examples
await jenkins.views.delete('/', 'MyView');
Code reference

src/views/views.getRelativePath.ts:23-30

Users

jenkins.users.get
Get information about user
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsUser>

Examples
const user = await jenkins.users.get('john');
Example result
{
  _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: [],
    },
    { _class: 'hudson.model.MyViewsProperty' },
    {
      _class: 'org.jenkinsci.plugins.displayurlapi.user.PreferredProviderUserProperty',
    },
    { _class: 'hudson.model.PaneStatusProperties' },
    { _class: 'jenkins.security.seed.UserSeedProperty' },
    {
      _class: 'hudson.search.UserSearchProperty',
      insensitiveSearch: true,
    },
    { _class: 'hudson.model.TimeZoneProperty' },
    { _class: 'hudson.security.HudsonPrivateSecurityRealm$Details' },
    {
      _class: 'hudson.tasks.Mailer$UserProperty',
      address: 'john@doe.com',
    }
  ]
}
Code reference

src/users/users.get.ts:68-69

jenkins.users.exists
Check whether user exists
Parameters
Returns

Promise<boolean>

Examples
const userExists = await jenkins.users.exists('john')
Code reference

src/users/users.exists.ts:28-29

jenkins.users.list
List users
Notes

This function allows usage of depth and tree parameters

Returns

Promise<Array<JenkinsUser>>

Examples
const users = await jenkins.users.list()
Example result
[
  {
    absoluteUrl: 'http://localhost:8080/user/admin',
    description: null,
    fullName: 'admin',
    id: 'admin',
    property: [
      {
        _class: 'com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty',
      },
      {
        _class: 'hudson.plugins.emailext.watching.EmailExtWatchAction$UserProperty',
        triggers: [],
      },
      {
        _class: 'hudson.model.MyViewsProperty',
      },
      {
        _class: 'org.jenkinsci.plugins.displayurlapi.user.PreferredProviderUserProperty',
      },
      {
        _class: 'hudson.model.PaneStatusProperties',
      },
      {
        _class: 'jenkins.security.seed.UserSeedProperty',
      },
      {
        _class: 'hudson.search.UserSearchProperty',
        insensitiveSearch: true,
      },
      {
        _class: 'hudson.model.TimeZoneProperty',
      },
      {
        _class: 'hudson.security.HudsonPrivateSecurityRealm$Details',
      },
      {
        _class: 'hudson.tasks.Mailer$UserProperty',
        address: 'admin@user.dev',
      },
      {
        _class: 'jenkins.security.ApiTokenProperty',
      },
      {
        _class: 'jenkins.security.LastGrantedAuthoritiesProperty',
      },
    ],
  },
  {
    absoluteUrl: 'http://localhost:8080/user/system',
    description: null,
    fullName: 'SYSTEM',
    id: 'SYSTEM',
    property: [
      {
        _class: 'jenkins.security.ApiTokenProperty',
      },
      {
        _class: 'com.cloudbees.plugins.credentials.UserCredentialsProvider$UserCredentialsProperty',
      },
      {
        _class: 'hudson.tasks.Mailer$UserProperty',
        address: null,
      },
      {
        _class: 'hudson.plugins.emailext.watching.EmailExtWatchAction$UserProperty',
        triggers: [],
      },
      {
        _class: 'hudson.model.MyViewsProperty',
      },
      {
        _class: 'org.jenkinsci.plugins.displayurlapi.user.PreferredProviderUserProperty',
      },
      {
        _class: 'hudson.model.PaneStatusProperties',
      },
      {
        _class: 'jenkins.security.seed.UserSeedProperty',
      },
      {
        _class: 'hudson.search.UserSearchProperty',
        insensitiveSearch: true,
      },
      {
        _class: 'hudson.model.TimeZoneProperty',
      },
    ],
  },
];
Code reference

src/users/users.list.ts:122-123

jenkins.users.create
Create user
Parameters
Returns

Promise<void>

Examples
await jenkins.users.create({
   username: 'john',
   fullname: 'john.doe',
   password: 'pass#1234',
   email: 'john.doe@company.com',
});
Code reference

src/users/users.create.ts:34-49

jenkins.users.delete
Delete user
Parameters
Returns

Promise<void>

Examples
await jenkins.users.delete('john');
Code reference

src/users/users.delete.ts:28-30

jenkins.users.whoAmI
Return information about currently authenticated user
Returns

Promise<JenkinsWhoAmI>

Examples
const user = await jenkins.users.whoAmI();
Example result
{
  _class: 'hudson.security.WhoAmI',
  anonymous: false,
  authenticated: true,
  authorities: [ 'authenticated' ],
  name: 'admin'
 }
Code reference

src/users/users.whoAmI.ts:37-38

jenkins.users.generateToken
Generate API token for currently authenticated user
Parameters
  • tokenName string new token name
Returns

Promise<JenkinsUserToken>

Examples
const tokenInfo = await jenkins.users.generateToken('ApiToken');
Example result
{
  tokenName: 'ApiToken',
  tokenUuid: 'ded6d423-7feb-4411-86c1-97bf82548074',
  tokenValue: '11c6e56d420f63c3ada149de4d52ba8dfe'
}
Code reference

src/users/users.generateToken.ts:38-51

jenkins.users.revokeToken
Revoke API token for currently authenticated user
Parameters
Returns

Promise<void>

Examples
await jenkins.users.revokeToken('ded6d423-7feb-4411-86c1-97bf82548074');
Code reference

src/users/users.revokeToken.ts:29-37

Nodes

jenkins.nodes.get
Get node information
Notes

This function allows usage of depth and tree parameters

Parameters
  • name string node name. For the built-in node use parentheses: (built-in)
Returns

Promise<JenkinsNode>

Examples
const node = await jenkins.nodes.get('(built-in)');
Example result
{
 _class: 'hudson.model.Hudson$MasterComputer',
 actions: [],
 assignedLabels: [ { name: 'another' }, { name: 'built-in' } ],
 description: 'the Jenkins controller's built-in node',
 displayName: 'Built-In Node',
 executors: [ {}, {} ],
 icon: 'computer.png',
 iconClassName: 'icon-computer',
 idle: true,
 jnlpAgent: false,
 launchSupported: true,
 loadStatistics: { _class: 'hudson.model.Label$1' },
 manualLaunchAllowed: true,
 monitorData: {
  'hudson.node_monitors.SwapSpaceMonitor': {
   _class: 'hudson.node_monitors.SwapSpaceMonitor$MemoryUsage2',
   availablePhysicalMemory: 5502185472,
   availableSwapSpace: 2147479552,
   totalPhysicalMemory: 8345554944,
   totalSwapSpace: 2147479552
  },
  'hudson.node_monitors.TemporarySpaceMonitor': {
   _class: 'hudson.node_monitors.DiskSpaceMonitorDescriptor$DiskSpace',
   timestamp: 1649971520244,
   path: '/tmp',
   size: 5669916672
  },
  'hudson.node_monitors.DiskSpaceMonitor': {
   _class: 'hudson.node_monitors.DiskSpaceMonitorDescriptor$DiskSpace',
   timestamp: 1649971520244,
   path: '/var/jenkins_home',
   size: 179432824832
  },
  'hudson.node_monitors.ArchitectureMonitor': 'Linux (amd64)',
  'hudson.node_monitors.ResponseTimeMonitor': {
   _class: 'hudson.node_monitors.ResponseTimeMonitor$Data',
   timestamp: 1649971520244,
   average: 0
  },
  'hudson.node_monitors.ClockMonitor': { _class: 'hudson.util.ClockDifference', diff: 0 }
 },
 numExecutors: 2,
 offline: false,
 offlineCause: null,
 offlineCauseReason: '',
 oneOffExecutors: [],
 temporarilyOffline: false
}
const node = await jenkins.nodes.get('MyNode');
Example result
{
 _class: 'hudson.slaves.SlaveComputer',
 actions: [],
 assignedLabels: [ { name: 'MyNode' } ],
 description: null,
 displayName: 'MyNode',
 executors: [ {} ],
 icon: 'computer-x.png',
 iconClassName: 'icon-computer-x',
 idle: true,
 jnlpAgent: true,
 launchSupported: false,
 loadStatistics: { _class: 'hudson.model.Label$1' },
 manualLaunchAllowed: true,
 monitorData: {
  'hudson.node_monitors.SwapSpaceMonitor': null,
  'hudson.node_monitors.TemporarySpaceMonitor': null,
  'hudson.node_monitors.DiskSpaceMonitor': null,
  'hudson.node_monitors.ArchitectureMonitor': null,
  'hudson.node_monitors.ResponseTimeMonitor': null,
  'hudson.node_monitors.ClockMonitor': null
 },
 numExecutors: 1,
 offline: true,
 offlineCause: null,
 offlineCauseReason: '',
 oneOffExecutors: [],
 temporarilyOffline: false,
 absoluteRemotePath: null
}
Code reference

src/nodes/nodes.get.ts:120-121

jenkins.nodes.exists
Check whether node exists
Parameters
  • name string node name. For the built-in node use parentheses: (built-in)
Returns

Promise<boolean>

Examples
const builtInNodeExists = await jenkins.nodes.exists('(built-in)');

const myNodeExists = await jenkins.nodes.exists('MyNode');
Code reference

src/nodes/nodes.exists.ts:30-31

jenkins.nodes.list
List nodes
Notes

This function allows usage of depth and tree parameters

Returns

Promise<Array<JenkinsNode>>

Examples
const nodes = await jenkins.nodes.list();
Example result
[
  {
    _class: 'hudson.model.Hudson$MasterComputer',
    actions: [],
    assignedLabels: [
      {
        name: 'another',
      },
      {
        name: 'built-in',
      },
    ],
    description: 'the Jenkins controller's built-in node',
    displayName: 'Built-In Node',
    executors: [{}, {}],
    icon: 'computer.png',
    iconClassName: 'icon-computer',
    idle: true,
    jnlpAgent: false,
    launchSupported: true,
    loadStatistics: {
      _class: 'hudson.model.Label$1',
    },
    manualLaunchAllowed: true,
    monitorData: {
      'hudson.node_monitors.SwapSpaceMonitor': {
        _class: 'hudson.node_monitors.SwapSpaceMonitor$MemoryUsage2',
        availablePhysicalMemory: 5482885120,
        availableSwapSpace: 2147479552,
        totalPhysicalMemory: 8345554944,
        totalSwapSpace: 2147479552,
      },
      'hudson.node_monitors.TemporarySpaceMonitor': {
        _class: 'hudson.node_monitors.DiskSpaceMonitorDescriptor$DiskSpace',
        timestamp: 1649971986539,
        path: '/tmp',
        size: 5669896192,
      },
      'hudson.node_monitors.DiskSpaceMonitor': {
        _class: 'hudson.node_monitors.DiskSpaceMonitorDescriptor$DiskSpace',
        timestamp: 1649971986538,
        path: '/var/jenkins_home',
        size: 179406462976,
      },
      'hudson.node_monitors.ArchitectureMonitor': 'Linux (amd64)',
      'hudson.node_monitors.ResponseTimeMonitor': {
        _class: 'hudson.node_monitors.ResponseTimeMonitor$Data',
        timestamp: 1649971986539,
        average: 0,
      },
      'hudson.node_monitors.ClockMonitor': {
        _class: 'hudson.util.ClockDifference',
        diff: 0,
      },
    },
    numExecutors: 2,
    offline: false,
    offlineCause: null,
    offlineCauseReason: '',
    oneOffExecutors: [],
    temporarilyOffline: false,
  },
  {
    _class: 'hudson.slaves.SlaveComputer',
    actions: [],
    assignedLabels: [
      {
        name: 'testing',
      },
    ],
    description: '',
    displayName: 'testing',
    executors: [{}],
    icon: 'computer-x.png',
    iconClassName: 'icon-computer-x',
    idle: true,
    jnlpAgent: true,
    launchSupported: false,
    loadStatistics: {
      _class: 'hudson.model.Label$1',
    },
    manualLaunchAllowed: true,
    monitorData: {
      'hudson.node_monitors.SwapSpaceMonitor': null,
      'hudson.node_monitors.TemporarySpaceMonitor': null,
      'hudson.node_monitors.DiskSpaceMonitor': null,
      'hudson.node_monitors.ArchitectureMonitor': null,
      'hudson.node_monitors.ResponseTimeMonitor': null,
      'hudson.node_monitors.ClockMonitor': null,
    },
    numExecutors: 1,
    offline: true,
    offlineCause: null,
    offlineCauseReason: '',
    oneOffExecutors: [],
    temporarilyOffline: false,
    absoluteRemotePath: null,
  },
]
Code reference

src/nodes/nodes.list.ts:131-132

jenkins.nodes.create
Create node
Parameters
Returns

Promise<void>

Examples
await jenkins.nodes.create('default-node');
await jenkins.nodes.create('my-node', {
  launcher: {
    '': '2',
    $class: 'hudson.plugins.sshslaves.SSHLauncher',
    credentialsId: 'd436fff1-af1c-45df-8cb6-3907d119b8fa',
    host: 'host',
    javaPath: '',
    jvmOptions: '',
    launchTimeoutSeconds: '',
    maxNumRetries: '',
    port: '22',
    prefixStartSlaveCmd: '',
    suffixStartSlaveCmd: '',
    retryWaitTime: '',
    sshHostKeyVerificationStrategy: {
      $class: 'hudson.plugins.sshslaves.verifiers.ManuallyTrustedKeyVerificationStrategy',
      requireInitialManualTrust: true,
      'stapler-class': 'hudson.plugins.sshslaves.verifiers.ManuallyTrustedKeyVerificationStrategy',
    },
    'stapler-class': 'hudson.plugins.sshslaves.SSHLauncher',
  },
  retentionStrategy: {
    $class: 'hudson.slaves.RetentionStrategy$Always',
    'stapler-class': 'hudson.slaves.RetentionStrategy$Always',
  },
  type: 'hudson.slaves.DumbSlave',
  mode: 'NORMAL',
  numExecutors: '1',
  remoteFS: '/home/jenkins',
  nodeDescription: 'Agent node description',
  labelString: 'agent-node-label',
  nodeProperties: {
    'stapler-class-bag': 'true',
  },
});
Code reference

src/nodes/nodes.create.ts:70-80

jenkins.nodes.copy
Copy node - create new node from existing one
Parameters
  • name string node name to copy from
  • newName string new node name
Returns

Promise<void>

Examples
await jenkins.nodes.copy('my-existing-node', 'my-new-node');
Code reference

src/nodes/nodes.copy.ts:29-39

jenkins.nodes.delete
Delete node
Parameters
Returns

Promise<void>

Examples
await jenkins.nodes.delete('my-node');
Code reference

src/nodes/nodes.delete.ts:28-30

jenkins.nodes.update
Update node configuration
Parameters
Returns

Promise<void>

Examples
await jenkins.nodes.update('my-node', {
  numExecutors: '3',
  remoteFS: '/home/jenkins',
  nodeDescription: 'Agent node description',
});
Code reference

src/nodes/nodes.update.ts:35-45

jenkins.nodes.setConfig
Update node configuration with xml config
Parameters
Returns

Promise<void>

Examples
await jenkins.nodes.setConfig(
  'my-node',
  `
<slave>
  <name>my-node</name>
  <numExecutors>1</numExecutors>
  <mode>NORMAL</mode>
  <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/>
  <launcher class="hudson.slaves.JNLPLauncher">
    <workDirSettings>
      <disabled>false</disabled>
      <internalDir>remoting</internalDir>
      <failIfWorkDirIsMissing>false</failIfWorkDirIsMissing>
    </workDirSettings>
    <webSocket>false</webSocket>
  </launcher>
  <label/>
  <nodeProperties/>
</slave>`,
);
Code reference

src/nodes/nodes.setConfig.ts:48-54

jenkins.nodes.configJson
Get node configuration as json object
Parameters
Returns

Promise<any>

Examples
const config = await jenkins.nodes.configJson('my-node');
Example result
{
  slave: {
    name: 'my-node',
    numExecutors: 1,
    mode: 'NORMAL',
    retentionStrategy: '',
    launcher: {
      workDirSettings: {
        disabled: false,
        internalDir: 'remoting',
        failIfWorkDirIsMissing: false,
      },
      webSocket: false,
    },
    label: '',
    nodeProperties: '',
  },
}
Code reference

src/nodes/nodes.configJson.ts:49-53

jenkins.nodes.configXml
Get node configuration as xml string
Parameters
Returns

Promise<string>

Examples
const configXml = await jenkins.nodes.configXml('my-node');
Example result
<?xml version="1.1" encoding="UTF-8"?>
<slave>
    <name>NodeConfig</name>
    <numExecutors>1</numExecutors>
    <mode>NORMAL</mode>
    <retentionStrategy class="hudson.slaves.RetentionStrategy$Always"/>
    <launcher class="hudson.slaves.JNLPLauncher">
        <workDirSettings>
            <disabled>false</disabled>
            <internalDir>remoting</internalDir>
            <failIfWorkDirIsMissing>false</failIfWorkDirIsMissing>
        </workDirSettings>
        <webSocket>false</webSocket>
    </launcher>
    <label></label>
    <nodeProperties/>
</slave>
Code reference

src/nodes/nodes.configXml.ts:47-48

jenkins.nodes.markOffline
Disable node - mark node as offline. Use this method to update offline reason as well.
Parameters
  • node string node name
  • reason string? reason for disabling this node (optional, default '')
Returns

Promise<void>

Examples
await jenkins.nodes.markOffline('my-node', 'Disconnected because of network errors');
Code reference

src/nodes/nodes.markOffline.ts:30-44

jenkins.nodes.bringOnline
Enable node - bring node back to online state
Parameters
Returns

Promise<void>

Examples
await jenkins.nodes.bringOnline('my-node');
Code reference

src/nodes/nodes.bringOnline.ts:29-38

Labels

jenkins.labels.get
Get node label information
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsLabel>

Examples
const label = await jenkins.labels.get('my-label');
Example result
{
  _class: 'hudson.model.labels.LabelAtom',
  actions: [{}],
  busyExecutors: 1,
  clouds: [
    {
      _class: 'org.csanchez.jenkins.plugins.kubernetes.NonConfigurableKubernetesCloud',
      actions: [{}],
    },
  ],
  description: null,
  idleExecutors: 0,
  loadStatistics: {
    _class: 'hudson.model.Label$1',
    availableExecutors: {},
    busyExecutors: {},
    connectingExecutors: {},
    definedExecutors: {},
    idleExecutors: {},
    onlineExecutors: {},
    queueLength: {},
    totalExecutors: {},
  },
  name: 'cypress-tests-1-productivity-develop-19',
  nodes: [
    {
      _class: 'org.csanchez.jenkins.plugins.kubernetes.KubernetesSlave',
      assignedLabels: [
        {
          name: 'cypress-tests-1-productivity-develop-19',
        },
        {
          name: 'cypress-tests-1-productivity-develop-19-mc4pv-s5803',
        },
      ],
      mode: 'EXCLUSIVE',
      nodeDescription: 'cypress-tests-1-productivity-develop-19-mc4pv',
      nodeName: 'cypress-tests-1-productivity-develop-19-mc4pv-s5803',
      numExecutors: 1,
    },
  ],
  offline: false,
  tiedJobs: [],
  totalExecutors: 1,
  propertiesList: [],
}
Code reference

src/labels/labels.get.ts:81-82

Plugins

jenkins.plugins.list
List plugins
Notes

This function allows usage of depth and tree parameters

Returns

Promise<Array<JenkinsPlugin>>

Examples
const plugins = await jenkins.plugins.list();
Example result
[
  {
    active: true,
    backupVersion: null,
    bundled: false,
    deleted: false,
    dependencies: [
      {
        optional: true,
        shortName: 'bouncycastle-api',
        version: '2.16.0',
      },
      {
        optional: true,
        shortName: 'command-launcher',
        version: '1.0',
      },
      {
        optional: true,
        shortName: 'jdk-tool',
        version: '1.0',
      },
      {
        optional: true,
        shortName: 'trilead-api',
        version: '1.0.4',
      },
      {
        optional: true,
        shortName: 'sshd',
        version: '3.0.1',
      },
    ],
    detached: false,
    downgradable: false,
    enabled: true,
    hasUpdate: false,
    longName: 'JavaScript GUI Lib: Moment.js bundle plugin',
    minimumJavaVersion: null,
    pinned: false,
    requiredCoreVersion: '1.580.1',
    shortName: 'momentjs',
    supportsDynamicLoad: 'YES',
    url: 'https://wiki.jenkins-ci.org/display/JENKINS/Moment.js',
    version: '1.1.1',
  },
]
Code reference

src/plugins/plugins.list.ts:79-80

Credentials

jenkins.credentials.<>.get
Get credential information
Notes

This function allows usage of depth and tree parameters

Parameters
  • id string credential id
  • domain string? credential domain. Default _.
Returns

Promise<JenkinsCredential>

Examples
const credential = await jenkins.credentials.system().get('credential-name');
const credential = await jenkins.credentials.folder('/my-folder').get('credential-name', 'my-domain');
const credential = await jenkins.credentials.user('user').get('credential-name');
Example result
{
  _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$CredentialsWrapper',
  description: 'some description',
  displayName: 'username/****** (some description)',
  fingerprint: null,
  fullName: 'my-folder/folder/my-domain/credential-name',
  id: 'credential-name',
  typeName: 'Username with password',
}
Code reference

src/credentials/credentials.get.ts:56-63

jenkins.credentials.<>.exists
Check whether the credential exists
Parameters
  • id string credential id
  • domain string? credential domain. Default _.
Returns

Promise<boolean>

Examples
const credentialExists = await jenkins.credentials.system().exists('credential-name');
const credentialExists = await jenkins.credentials.folder('/my-folder').exists('credential-name', 'my-domain');
const credentialExists = await jenkins.credentials.user('user').exists('credential-name');
Code reference

src/credentials/credentials.exists.ts:41-47

jenkins.credentials.<>.list
List credentials
Notes

This function allows usage of depth and tree parameters

Parameters
  • domain string? credential domain. Default _.
Returns

Promise<Array<JenkinsCredential>>

Examples
const credential = await jenkins.credentials.system().list();
const credential = await jenkins.credentials.folder('/my-folder').list();
const credential = await jenkins.credentials.user('user').list();
Example result
[
  {
    description: 'some description',
    displayName: 'username/****** (some description)',
    fingerprint: null,
    fullName: 'my-folder/folder/my-domain/credential-name',
    id: 'credential-name',
    typeName: 'Username with password',
  }
]
Code reference

src/credentials/credentials.list.ts:56-64

jenkins.credentials.<>.create
Create credential
Parameters
  • xmlConfig string credential configuration as xml string
  • domain string? credential domain. Default _.
Returns

Promise<void>

Examples
await jenkins.credentials.system().create(`
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl plugin="credentials@2.6.1">
   <scope>GLOBAL</scope>
   <id>credential-name</id>
   <description>some description</description>
   <username>username</username>
   <password>password</password>
   <usernameSecret>false</usernameSecret>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>`
);
await jenkins.credentials.folder('/my-folder').create(`...`);
await jenkins.credentials.user('user').create(`...`);
Code reference

src/credentials/credentials.create.ts:50-58

jenkins.credentials.<>.delete
Delete credential
Parameters
  • id string credential id
  • domain string? credential domain. Default _.
Returns

Promise<void>

Examples
await jenkins.credentials.system().delete('credential-name');
await jenkins.credentials.system().delete('credential-name', 'my-domain');
await jenkins.credentials.folder('/my-folder').delete('credential-name');
await jenkins.credentials.user('user').delete('credential-name');
Code reference

src/credentials/credentials.delete.ts:45-53

jenkins.credentials.<>.setConfig
Update credential configuration
Parameters
  • id string credential id
  • xmlConfig string credential configuration as xml string
  • domain string? credential domain. Default _.
Returns

Promise<void>

Examples
await jenkins.credentials.system().setConfig('credential-name',
  `
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl plugin="credentials@2.6.1">
  <scope>GLOBAL</scope>
  <id>credential-name</id>
  <description>some description</description>
  <username>username_updated</username>
  <password>password</password>
  <usernameSecret>false</usernameSecret>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>`
);
await jenkins.credentials.folder('/my-folder').setConfig('credential-name', `...`);
await jenkins.credentials.user('user').setConfig('credential-name', `...`);
Code reference

src/credentials/credentials.setConfig.ts:52-61

jenkins.credentials.<>.configJson
Get credentials config as json object
Parameters
  • id string credential id
  • domain string? credential domain. Default _.
Returns

Promise<any>

Examples
const config = await jenkins.credentials.system().configJson('credential-name');
const config = await jenkins.credentials.system().configJson('credential-name', 'my-domain');
const config = await jenkins.credentials.folder('/my-folder').configJson('credential-name');
const config = await jenkins.credentials.user('user').configJson('credential-name');
Example result
{
  'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl': {
    scope: 'GLOBAL',
    id: 'credential-name',
    description: 'some description',
    username: 'username',
    password: { 'secret-redacted': '' },
    usernameSecret: false,
  }
}
Code reference

src/credentials/credentials.configJson.ts:60-70

jenkins.credentials.<>.configXml
Get credentials config as xml string
Parameters
  • id string credential id
  • domain string? credential domain. Default _.
Returns

Promise<string>

Examples
const config = await jenkins.credentials.system().configXml('credential-name');
const config = await jenkins.credentials.folder('/my-folder').configXml('credential-name');
const config = await jenkins.credentials.user('user').configXml('credential-name');
Example result
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl plugin="credentials@2.6.1">
    <scope>GLOBAL</scope>
    <id>credential-name</id>
    <description>some description</description>
    <username>username</username>
    <password>
        <secret-redacted/>
    </password>
    <usernameSecret>false</usernameSecret>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
Code reference

src/credentials/credentials.configXml.ts:54-61

Credentials domains

jenkins.credentials.<>.domains.get
Get credential domain
Notes

This function allows usage of depth and tree parameters

Parameters
Returns

Promise<JenkinsCredentialDomain>

Examples
await jenkins.credentials.system().domains.get('github');
Example result
{
  _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper',
  credentials: [],
  description: null,
  displayName: 'github',
  fullDisplayName: 'System » github',
  fullName: 'system/github',
  global: false,
  urlName: 'github',
};
await jenkins.credentials.user('admin').domains.get('github');
Example result
{
  _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper',
  credentials: [],
  description: null,
  displayName: 'github',
  fullDisplayName: 'User: admin » User » github',
  fullName: 'user:admin/user/github',
  global: false,
  urlName: 'github',
}
await jenkins.credentials.folder('/my-folder').domains.get('github');
Example result
{
  _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper',
  credentials: [],
  description: null,
  displayName: 'github',
  fullDisplayName: 'my-folder » Folder » github',
  fullName: 'my-folder/folder/github',
  global: false,
  urlName: 'github',
}
Code reference

src/credentials/domains/domains.get.ts:82-88

jenkins.credentials.<>.domains.exists
Check whether credential domain exists
Parameters
Returns

Promise<boolean>

Examples
const domainExists = await jenkins.credentials.system().domains.exists('github');
const domainExists = await jenkins.credentials.folder('/my-folder').domains.exists('github');
const domainExists = await jenkins.credentials.user('user').domains.exists('github');
Code reference

src/credentials/domains/domains.exists.ts:40-45

jenkins.credentials.<>.domains.list
List credential domains
Notes

This function allows usage of depth and tree parameters

Returns

Promise<Array<JenkinsCredentialDomain>>

Examples
const domains = await jenkins.credentials.system().domains.list();
Example result
[
  {
    _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper',
    credentials: [],
    description:
      'Credentials that should be available irrespective of domain specification to requirements matching.',
    displayName: 'Global credentials (unrestricted)',
    fullDisplayName: 'System » Global credentials (unrestricted)',
    fullName: 'system/_',
    global: true,
    urlName: '_',
  },
  {
    _class: 'com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper',
    credentials: [],
    description: null,
    displayName: 'github',
    fullDisplayName: 'System » github',
    fullName: 'system/github',
    global: false,
    urlName: 'github',
  },
]
const domains = await jenkins.credentials.folder('/my-folder').domains.list();
const domains = await jenkins.credentials.user('user').domains.list();
Code reference

src/credentials/domains/domains.list.ts:69-86

jenkins.credentials.<>.domains.create
Create credential domain
Parameters
  • xmlContent string domain configuration
Returns

Promise<void>

Examples
await jenkins.credentials.system().domains.create(`
 <com.cloudbees.plugins.credentials.domains.Domain plugin="credentials@2.6.1">
     <name>github</name>
     <specifications>
         <com.cloudbees.plugins.credentials.domains.HostnameSpecification>
             <includes>github.com</includes>
             <excludes/>
         </com.cloudbees.plugins.credentials.domains.HostnameSpecification>
     </specifications>
 </com.cloudbees.plugins.credentials.domains.Domain>`
);
await jenkins.credentials.folder('/my-folder').domains.create(`...`);
await jenkins.credentials.user('user').domains.create(`...`);
Code reference

src/credentials/domains/domains.create.ts:50-57

jenkins.credentials.<>.domains.delete
Delete credential domain
Parameters
Returns

Promise<void>

Examples
await jenkins.credentials.system().domains.delete('github');
await jenkins.credentials.folder('/my-folder').domains.delete('github');
await jenkins.credentials.user('user').domains.delete('github');
Code reference

src/credentials/domains/domains.delete.ts:40-47

jenkins.credentials.<>.domains.setConfig
Set credential domain configuration as xml string
Parameters
  • domain string domain name
  • xmlConfig string domain xml configuration
Returns

Promise<void>

Examples
await jenkins.credentials.system().domains.setConfig('github', `
 <com.cloudbees.plugins.credentials.domains.Domain plugin="credentials@2.6.1">
     <name>github_updated</name>
     <specifications>
         <com.cloudbees.plugins.credentials.domains.HostnameSpecification>
             <includes>github.com</includes>
             <excludes/>
         </com.cloudbees.plugins.credentials.domains.HostnameSpecification>
     </specifications>
 </com.cloudbees.plugins.credentials.domains.Domain>`
);
await jenkins.credentials.folder('/my-folder').domains.setConfig('github', `...`);
await jenkins.credentials.user('user').domains.setConfig('github', `...`);
Code reference

src/credentials/domains/domains.setConfig.ts:51-59

jenkins.credentials.<>.domains.configJson
Get credential domain configuration as json object
Parameters
Returns

Promise<any>

Examples
const domain = await jenkins.credentials.system().domains.configJson('github');
const domain = await jenkins.credentials.folder('/my-folder').domains.configJson('github');
const domain = await jenkins.credentials.user('user').domains.configJson('github');
Example result
{
  'com.cloudbees.plugins.credentials.domains.Domain': {
    name: 'github',
    specifications: {
      'com.cloudbees.plugins.credentials.domains.HostnameSpecification': {
        includes: 'github.com',
        excludes: '',
      }
    }
  }
}
Code reference

src/credentials/domains/domains.configJson.ts:55-64

jenkins.credentials.<>.domains.configXml
Get credential domain configuration as xml string
Parameters
Returns

Promise<string>

Examples
const domain = await jenkins.credentials.system().domains.configXml('github');
const domain = await jenkins.credentials.folder('/my-folder').domains.configXml('github');
const domain = await jenkins.credentials.user('user').domains.configXml('github');
Example result
<com.cloudbees.plugins.credentials.domains.Domain plugin="credentials@2.6.1">
    <name>github</name>
    <specifications>
        <com.cloudbees.plugins.credentials.domains.HostnameSpecification>
            <includes>github.com</includes>
            <excludes></excludes>
        </com.cloudbees.plugins.credentials.domains.HostnameSpecification>
    </specifications>
</com.cloudbees.plugins.credentials.domains.Domain>
Code reference

src/credentials/domains/domains.configXml.ts:52-58

Keywords