Java API操作Jenkins和自定义Java构建镜像

文章介绍了如何使用Java操作Jenkins,包括通过API获取json和xml格式的数据,以及利用java-client-api进行交互。还展示了如何创建自定义Java构建镜像,该镜像包含了预装的Jenkins插件、Maven和Node.js,且设置了国内镜像源和初始化脚本以简化设置流程。
摘要由CSDN通过智能技术生成

1、Java操作Jenkins

1.1、Jenkins API支持格式json和xml

# json格式,{host}/api/json
http://192.168.245.139:8080/api/json
# 视图接口,json格式
http://192.168.245.139:8080/user/admin/my-views/view/test_view/api/json
# 任务接口,json格式
http://192.168.245.139:8080/job/cms-main/api/json

# xml格式,{host}/api/xml
http://192.168.245.139:8080/api/xml
# 视图接口,xml格式
http://192.168.245.139:8080/user/admin/my-views/view/test_view/api/xml
# 任务接口,xml格式
http://192.168.245.139:8080/job/colorcat/api/xml

1.2、Java API操作

java操作jenkins使用的依赖包java-client-api(https://github.com/jenkinsci/java-client-api)
maven配置文件pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <groupId>com.penngo.jenkins</groupId>
    <artifactId>jenkins_tools</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>3.0.12</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>com.offbytwo.jenkins</groupId>
            <artifactId>jenkins-client</artifactId>
            <version>0.3.8</version>
        </dependency>
    </dependencies>
</project>

JenkinsTool.java,主要是从一个已配置好的jenkins里面下载需要的插件,提供给后边的定制jenkins镜像使用

package com.penngo.jenkins;

import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.*;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

public class JenkinsTool {
    static final String JENKINS_URL = "http://192.168.245.139:8080/";
    static final String JENKINS_USERNAME = "admin";
    static final String JENKINS_PASSWORD = "admin";
    JenkinsServer jenkinsServer = null;
    JenkinsHttpClient jenkinsHttpClient = null;
    public JenkinsTool(){
        try {
            jenkinsServer = new JenkinsServer(new URI(JENKINS_URL), JENKINS_USERNAME, JENKINS_PASSWORD);
            jenkinsHttpClient = new JenkinsHttpClient(new URI(JENKINS_URL), JENKINS_USERNAME, JENKINS_PASSWORD);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取视图基本信息
     */
    public void getView() throws Exception{
            System.out.println("=======视图=====");
            jenkinsServer.getViews().forEach((key,view)->{
                System.out.println("视图:" + key + "," + view.getName() + "," + view.getUrl() + "," + view.getDescription());
            });
    }
    /**
     * 获取 Job 基本信息
     */
    public void getJob() throws Exception{

        System.out.println("=======任务=====");
        jenkinsServer.getJobs().forEach((key, job)->{
            System.out.printf("Name:%s,BuildNumber:%s\n", job.getName() , job.getUrl());
            try {
                JobWithDetails jobTemp = jenkinsServer.getJob(job.getName());
                Build build = jobTemp.getLastBuild();
                System.out.printf("buildNumber:%s", build.getNumber());
            }
            catch(Exception e){
                e.printStackTrace();
            }
        });
    }
    /**
     * 获取 Jenkins 插件信息
     */
    public void getPlugins() throws Exception{
        PluginManager pluginManager =jenkinsServer.getPluginManager();
        // 获取插件列表
        List<Plugin> plugins = pluginManager.getPlugins();
        String downloadurl = "https://mirror.tuna.tsinghua.edu.cn/jenkins/plugins";

        for (Plugin plugin:plugins){
            // https://updates.jenkins.io/download/plugins/ant/487.vd79d090d4ea_e/ant.hpi
            // https://mirror.tuna.tsinghua.edu.cn/jenkins/plugins/ant/487.vd79d090d4ea_e/ant.hpi

            System.out.printf("plugin:%s, %s, %s, %s, %s, %s\n", plugin.getUrl(),plugin.getVersion(),plugin.getShortName(),plugin.getLongName(),plugin.getSupportsDynamicLoad(),plugin.getDependencies());
            String url = String.format("%s/%s/%s/%s.hpi",downloadurl,plugin.getShortName(),plugin.getVersion(),plugin.getShortName());
            System.out.printf("download url:%s\n", url);
            // 下载插件到本地
            FileUtils.copyURLToFile(new URL(url), new File("target/plugins", String.format("%s.hpi", plugin.getShortName())));
        }
    }

    public static void main(String[] args) throws Exception{
        JenkinsTool jenkins = new JenkinsTool();
//        jenkins.getView();
//        jenkins.getJob();
        jenkins.getPlugins();
    }
}

2、自定义Java构建镜像

镜像包含打包了常用插件的Jenkins(跳过初始化密码和插件安装),构建Maven工具,常用的Maven依赖包
Dockerfile文件内容

FROM jenkins/jenkins:2.346.3-jdk8
# 先使用root用户下载软件
USER root
# 设置镜像的apt源
COPY --chown=root:root sources.list /etc/apt/sources.list
# 设置jenkins用户公钥私钥
COPY --chown=jenkins:jenkins .ssh /var/jenkins_home/.ssh
# 把上边java下载的jenkins插件添加到镜像
COPY --chown=jenkins:jenkins target/plugins /usr/share/jenkins/ref/plugins/
# 添加初始化脚本,用户提前设置用户名和密码
COPY --chown=jenkins:jenkins init_user_password.groovy /usr/share/jenkins/ref/init.groovy.d/init_user_password.groovy

# maven和nodejs安装包
COPY --chown=jenkins:jenkins tool/apache-maven-3.8.6 /var/jenkins_home/tools/apache-maven-3.8.6
ENV MAVEN_HOME=/var/jenkins_home/tools/apache-maven-3.8.6

COPY --chown=jenkins:jenkins tool/node-v14.21.3-linux-x64 /var/jenkins_home/tools/node-v14.21.3-linux-x64
ENV NODE_HOME=/var/jenkins_home/tools/node-v14.21.3-linux-x64

ENV PATH=$MAVEN_HOME/bin:$NODE_HOME/bin:$PATH

# 把本地maven仓库的依赖包拷到镜像
COPY --chown=jenkins:jenkins /root/.m2 /var/jenkins_home/.m2

# 设置root密码
RUN echo root:123456 | chpasswd

USER jenkins

EXPOSE 8080 50000
# Djenkins.install.runSetupWizard=false 代表跳过jenkins初始化阶段
ENV JAVA_OPTS=-Djenkins.install.runSetupWizard=false -Duser.timezone=GMT+08

修改debian系统的包下载为国内源sources.list

deb https://mirrors.aliyun.com/debian/ bullseye main non-free contrib
deb-src https://mirrors.aliyun.com/debian/ bullseye main non-free contrib
deb https://mirrors.aliyun.com/debian-security/ bullseye-security main
deb-src https://mirrors.aliyun.com/debian-security/ bullseye-security main
deb https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib
deb-src https://mirrors.aliyun.com/debian/ bullseye-updates main non-free contrib
deb https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib
deb-src https://mirrors.aliyun.com/debian/ bullseye-backports main non-free contrib

Jenkins初始化脚本init_user_password.groovy

#!groovy
import hudson.security.*
import jenkins.model.*

def instance = Jenkins.getInstance()
def hudsonRealm = new HudsonPrivateSecurityRealm(false)
def users = hudsonRealm.getAllUsers()
users_s = users.collect { it.toString() }

// 设置初始帐号和密码
if ("admin" in users_s) {
    println "Admin user already exists - updating password"

    def user = hudson.model.User.get('admin');
    def password = hudson.security.HudsonPrivateSecurityRealm.Details.fromPlainPassword('admin')
    user.addProperty(password)
    user.save()
}
else {
    println "--> creating local admin user"

    hudsonRealm.createAccount('admin', 'admin')
    instance.setSecurityRealm(hudsonRealm)

    def strategy = new FullControlOnceLoggedInAuthorizationStrategy()
    instance.setAuthorizationStrategy(strategy)
    instance.save()
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

penngo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值