使用 nodejs 操作 jenkins 的 api
1.连接 jenkins
js
// jenkins的版本需要指定为0.28.0,如果是1.0.0版本的话需要import导入
const Jenkins = require("jenkins");
const jenkins = new Jenkins({
// http://用户名:密码@jenkins的访问地址
baseUrl: "https://账户名称:密码@jenkins.cghbh.com",
// 需要加上这一行,否则调用jenkins的接口会报403错误
crumbIssuer: true,
});
module.exports = jenkins;
2.获取 jenkins 的服务信息
js
await jenkins.info();
3.获取指定项目的第 n 次构建信息
用法
js
// name:jenkins的工程名称,number:第n次第构建 name和number参数必传
await jenkins.build.get(name:string, number: number)
await jenkins.build.get("example", 1);
返回值
json
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user admin",
"userId": "admin",
"userName": "admin"
}
]
},
{},
{},
{
"_class": "org.jenkinsci.plugins.displayurlapi.actions.RunDisplayAction"
}
],
"artifacts": [],
"building": false,
"description": null,
"displayName": "#1",
"duration": 34823,
"estimatedDuration": 16457,
"executor": null,
"fullDisplayName": "fe-docs #1",
"id": "1",
"keepLog": false,
"number": 1,
"queueId": 1,
"result": "FAILURE",
"timestamp": 1659340509308,
"url": "http://139.198.177.30:9524/job/fe-docs/1/",
"builtOn": "",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [],
"kind": null
},
"culprits": []
}
4.获取指定项目的第 n 次构建的 log 日志信息
用法
js
await jenkins.build.log(name:string, number: number)
await jenkins.build.log("example", 1);
返回值
shell
Started by user admin
Running as SYSTEM
Building in workspace /var/jenkins_home/workspace/fe-docs
The recommended git tool is: NONE
No credentials specified
> git rev-parse --resolve-git-dir /var/jenkins_home/workspace/fe-docs/.git # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/cghbh/fe-docs.git # timeout=10
Fetching upstream changes from https://github.com/cghbh/fe-docs.git
> git --version # timeout=10
> git --version # 'git version 2.30.2'
> git fetch --tags --force --progress -- https://github.com/cghbh/fe-docs.git +refs/heads/*:refs/remotes/origin/* # timeout=10
> git rev-parse refs/remotes/origin/master^{commit} # timeout=10
Checking out Revision e9ef572d39c799bfedcc8eb652d21bdd075214ff (refs/remotes/origin/master)
> git config core.sparsecheckout # timeout=10
> git checkout -f e9ef572d39c799bfedcc8eb652d21bdd075214ff # timeout=10
Commit message: "文档更新"
> git rev-list --no-walk e9ef572d39c799bfedcc8eb652d21bdd075214ff # timeout=10
[Checks API] No suitable checks publisher found.
[fe-docs] $ /bin/bash /tmp/jenkins1110292205872512816.sh
/var/jenkins_home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node14/bin:/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/var/jenkins_home/workspace/fe-docs
Sending build context to Docker daemon 2.442MB
Step 1/8 : FROM node:14
---> 326f034bd14b
Step 2/8 : RUN mkdir -p /home/fe-docs
---> Using cache
---> 32bf898eb363
Step 3/8 : WORKDIR /home/fe-docs
---> Using cache
---> 207cfee203bb
Step 4/8 : COPY . /home/fe-docs
---> Using cache
---> b1fa0df62649
Step 5/8 : RUN npm config set registry https://registry.npm.taobao.org
---> Using cache
---> e94624c4e81d
Step 6/8 : RUN npm i docsify-cli -g
---> Using cache
---> 950d6de3feb5
Step 7/8 : EXPOSE 3000
---> Using cache
---> 4f8ef8898fa8
Step 8/8 : CMD docsify serve docs
---> Using cache
---> 4a416e1b4091
Successfully built 4a416e1b4091
Successfully tagged fe-docs:latest
l【fe-docs】已运行,正在重启。。。
fedocs
fedocs
889c2f43dde80a9e8fd79ccd5fef169322bb1f7ef2d01911620d38bd5b70f5aa
构建完成
[Checks API] No suitable checks publisher found.
Finished: SUCCESS
5.停止指定项目的第 n 次构建
用法
name:jenkins 的工程名称,number:第 n 次构建
js
await jenkins.build.stop({ name, number });
6.触发指定 jenkins 的构建
用法
js
// const result = await jenkins.job.build('Job的名称');
await jenkins.job.build("example");
输出
shell
// 返回的数字是构建的buildId,这个后面跟jenkins.build.logStream获取实时构建日志有关,请注意
275
7.获取 jenkins 的配置信息,以 xml 返回
用法
js
await jenkins.job.config("example");
返回
xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.niwodai</groupId>
<artifactId>inf-deployment</artifactId>
<version>2.0.0</version>
</parent>
<groupId>${user.project.groupId}</groupId>
<artifactId>${user.project.artifactId}</artifactId>
<version>${user.project.version}-SNAPSHOT</version>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<!-- 抛弃assembly id的值,防止追加到包名后面 -->
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<!-- 描述文件路径 -->
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<!--名字任意 -->
<id>make-assembly</id>
<!-- 绑定到package生命周期阶段上 -->
<phase>package</phase>
<goals>
<!-- 只运行一次 -->
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
8.删除 jenkins 的 job
用法:注意,一定要慎重操作此 api
js
await jenkins.job.destroy("example");
9.判断当前的 jenkins 工程是否存在
用法
返回输出 bool 值
js
// const result = await jenkins.job.exists('Job名称');
const result = await jenkins.job.exists("create-demo1");
10.列出指定用户下所有的 jenkins 工程
用法
js
await jenkins.job.list();
输出:
json
[
{
"_class": "hudson.model.FreeStyleProject",
"name": "blog-fe",
"url": "http://139.198.177.30:9526/job/blog-fe/",
"color": "blue"
},
{
"_class": "hudson.model.FreeStyleProject",
"name": "devops-system",
"url": "http://139.198.177.30:9526/job/devops-system/",
"color": "blue"
},
{
"_class": "hudson.model.FreeStyleProject",
"name": "main-dcos-important",
"url": "http://139.198.177.30:9526/job/main-dcos-important/",
"color": "blue"
},
{
"_class": "hudson.model.FreeStyleProject",
"name": "main-docs",
"url": "http://139.198.177.30:9526/job/main-docs/",
"color": "blue"
},
{
"_class": "hudson.model.FreeStyleProject",
"name": "main-docs-important",
"url": "http://139.198.177.30:9526/job/main-docs-important/",
"color": "blue"
}
]
11.获取 Job 的详细信息
js
// const result = await jenkins.job.get('Job名称');
const result = await jenkins.job.get("main-docs-important");
输出结果如下:
json
{
"_class": "hudson.model.FreeStyleProject",
"actions": [
{},
{},
{},
{},
{},
{
"_class": "org.jenkinsci.plugins.displayurlapi.actions.JobDisplayAction"
},
{
"_class": "com.cloudbees.plugins.credentials.ViewCredentialsAction"
}
],
"description": "",
"displayName": "main-docs-important",
"displayNameOrNull": null,
"fullDisplayName": "main-docs-important",
"fullName": "main-docs-important",
"name": "main-docs-important",
"url": "http://139.198.177.30:9526/job/main-docs-important/",
"buildable": true,
"builds": [
{
"_class": "hudson.model.FreeStyleBuild",
"number": 3,
"url": "http://139.198.177.30:9526/job/main-docs-important/3/"
},
{
"_class": "hudson.model.FreeStyleBuild",
"number": 2,
"url": "http://139.198.177.30:9526/job/main-docs-important/2/"
},
{
"_class": "hudson.model.FreeStyleBuild",
"number": 1,
"url": "http://139.198.177.30:9526/job/main-docs-important/1/"
}
],
"color": "blue",
"firstBuild": {
"_class": "hudson.model.FreeStyleBuild",
"number": 1,
"url": "http://139.198.177.30:9526/job/main-docs-important/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": 24,
"url": "http://139.198.177.30:9526/job/main-docs-important/24/"
},
"lastCompletedBuild": {
"_class": "hudson.model.FreeStyleBuild",
"number": 24,
"url": "http://139.198.177.30:9526/job/main-docs-important/24/"
},
"lastFailedBuild": null,
"lastStableBuild": {
"_class": "hudson.model.FreeStyleBuild",
"number": 24,
"url": "http://139.198.177.30:9526/job/main-docs-important/24/"
},
"lastSuccessfulBuild": {
"_class": "hudson.model.FreeStyleBuild",
"number": 24,
"url": "http://139.198.177.30:9526/job/main-docs-important/24/"
},
"lastUnstableBuild": null,
"lastUnsuccessfulBuild": null,
"nextBuildNumber": 25,
"property": [
{
"_class": "com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty"
}
],
"queueItem": null,
"concurrentBuild": false,
"disabled": false,
"downstreamProjects": [],
"labelExpression": null,
"scm": {
"_class": "hudson.plugins.git.GitSCM"
},
"upstreamProjects": []
}
12.获取 Job 构建的日志流
- jenkins.build.logStream(options)
- name (String):Job 的名称
- number (Integer):第几次构建
- type (String, enum: text, html, default: text): 输出的格式,默认 text
- delay (Integer, default: 1000):获取日志延迟时间
js
const logStream = await jenkins.build.logStream(
"main-dcos-important",
12,
"text",
2000
);
输出的内容:以流的形式返回