【Jenkins】远程API接口:Java 包装接口使用示例

2023-12-21 17:43:13

jenkins-rest 库是一个面向对象的 Java 项目,它通过编程方式提供对 Jenkins REST API 的访问,以访问 Jenkins 提供的一些远程 API。它使用 jclouds 工具包构建,可以轻松扩展以支持更多 REST 端点。其功能集不断发展,用户可以通过拉取请求贡献新的端点。在当前状态下,使用此库可以提交作业、跟踪其通过队列的进度并监控其执行直到完成,并获取构建状态。目前提供的服务包括:

  • 端点定义(属性或环境变量)
  • 身份验证(通过属性或环境变量进行基本和 API 令牌)
  • Crumbs Issuer 支持(自动检测 crumbs)
  • 文件夹支持
  • 作业 API(构建、构建信息、带参数构建、配置、创建、删除、描述、禁用、启用、作业信息、最后构建编号、最后构建时间戳和渐进文本)
  • 插件管理器 API(安装必要的插件、列出当前插件)
  • 队列 API(取消、列出队列项、查询队列项)
  • 统计 API(总体负载)
  • 系统 API(系统信息)

引入依赖jar包

注意,不同的版本要求的jdk版本不一致,可以在这里查看,
https://github.com/cdancy/jenkins-rest

以下示例版本1.0.2要求jdk11

<dependency>
    <groupId>io.github.cdancy</groupId>
    <artifactId>jenkins-rest</artifactId>
    <version>1.0.2</version>
    <classifier>all</classifier>
</dependency>

使用示例

假设Jenkins地址是 http://192.168.56.114:8080

1、初始化客户端链接

private static JenkinsClient client;
private static final String JENKINS_URL = "http://192.168.56.114:8080";

public static void init() {
    client = JenkinsClient.builder()
            .endPoint(JENKINS_URL) // Jenkins地址
            .credentials("admin:admin123") // 账号密码.
            .build();

    SystemInfo systemInfo = client.api().systemApi().systemInfo();
    log.info("jenkinsVersion: {}", systemInfo.jenkinsVersion());
}

2、查询任务列表

public static void jobs() {
    JobsApi jobsApi = client.api().jobsApi();
    JobList jobList = jobsApi.jobList("");
    jobList.jobs().forEach(job -> System.out.println(job.name()));
}

3、触发无参任务构建

返回的value不为null,代表执行成功

public static void build() {
    JobsApi jobsApi = client.api().jobsApi();
    // 必须是无参数任务
    String jobName = "job_no_params";
    IntegerResponse response = jobsApi.build("", jobName);
    System.out.println("build = " + response);
    // 返回的value不为null,代表执行成功
    if (response.value() != null) {
        System.out.println("任务执行成功:" + jobName);
    } else {
        System.out.println("任务执行失败:" + response.errors());
    }
}

4、触发有参任务构建

这里的任务必须是带参数的,如果调用的无参任务,会报错!

返回的value不为null,代表执行成功

public static void buildWithParameters() {
    JobsApi jobsApi = client.api().jobsApi();
    Map<String, List<String>> properties = new HashMap<>();
    properties.put("ENV", Collections.singletonList("prod"));
    // 必须是有参数任务
    String jobName = "job_with_params";
    IntegerResponse response = jobsApi.buildWithParameters("", jobName, properties);
    System.out.println("buildWithParameters = " + response);
    // 返回的value不为null,代表执行成功
    if (response.value() != null) {
        System.out.println("任务执行成功:" + jobName);
    } else {
        System.out.println("任务执行失败:" + response.errors());
    }
}

5、创建新任务

创任务必须传入xml配置数据

public static void createJob() {
    JobsApi jobsApi = client.api().jobsApi();
    String configXml = "<?xml version='1.1' encoding='UTF-8'?>\n" +
            "<flow-definition plugin=\"workflow-job@1385.vb_58b_86ea_fff1\">\n" +
            "  <actions>\n" +
            "    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobAction plugin=\"pipeline-model-definition@2.2151.ve32c9d209a_3f\"/>\n" +
            "    <org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction plugin=\"pipeline-model-definition@2.2151.ve32c9d209a_3f\">\n" +
            "      <jobProperties/>\n" +
            "      <triggers/>\n" +
            "      <parameters/>\n" +
            "      <options/>\n" +
            "    </org.jenkinsci.plugins.pipeline.modeldefinition.actions.DeclarativeJobPropertyTrackerAction>\n" +
            "  </actions>\n" +
            "  <description></description>\n" +
            "  <keepDependencies>false</keepDependencies>\n" +
            "  <properties/>\n" +
            "  <definition class=\"org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition\" plugin=\"workflow-cps@3826.v3b_5707fe44da_\">\n" +
            "    <script>pipeline {\n" +
            "    agent any\n" +
            "    environment {\n" +
            "        CC = &apos;clang&apos;\n" +
            "    }\n" +
            "    stages {\n" +
            "        stage(&apos;Example&apos;) {\n" +
            "            environment {\n" +
            "                DEBUG_FLAGS = &apos;-g&apos;\n" +
            "            }\n" +
            "            steps {\n" +
            "                sh &apos;printenv&apos;\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}</script>\n" +
            "    <sandbox>true</sandbox>\n" +
            "  </definition>\n" +
            "  <triggers/>\n" +
            "  <disabled>false</disabled>\n" +
            "</flow-definition>\n";
    String newJobName = "java_api_02";
    RequestStatus status = jobsApi.create("", newJobName, configXml);
    if (status.value()) {
        System.out.println("任务创建成功: " + newJobName);
    } else {
        System.out.println("任务创建失败: " + newJobName);
    }
}

6、删除任务

public static void delete() {
    JobsApi jobsApi = client.api().jobsApi();
    String jobName = "api05";
    RequestStatus status = jobsApi.delete("", jobName);
    System.out.println("delete = " + status);
    if (status.value()){
        System.out.println("任务删除成功: " + jobName);
    }else{
        System.out.println("任务删除失败: " + status.errors());
    }
}

7、禁用/启用任务

public static void disable() {
    JobsApi jobsApi = client.api().jobsApi();
    boolean flag = jobsApi.disable("", "api01");
    System.out.println("disable = " + flag);
}

public static void enable() {
    JobsApi jobsApi = client.api().jobsApi();
    boolean flag = jobsApi.enable("", "api01");
    System.out.println("enable = " + flag);
}

8、查询最近构建序号

public static void lastBuildNumber() {
    JobsApi jobsApi = client.api().jobsApi();
    String jobName = "job_no_params";
    Integer lastBuildNumber = jobsApi.lastBuildNumber("", jobName);
    System.out.println("lastBuildNumber = " + lastBuildNumber);
}

9、Jenkins服务负载情况查询

public static void overallLoad() {
    OverallLoad overallLoad = client.api().statisticsApi().overallLoad();
    System.out.println("overallLoad = " + overallLoad);
}

文章来源:https://blog.csdn.net/wlddhj/article/details/135135621
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。