一、Jenkins Api简介

Jenkins 对外暴露的动作交付入口
为外部程序提供入口,可以控制Jenkins
支持协议 - Http
Api 接口支持用户名、密码认证
Jenkins Api支持的典型功能:运行Job、查看任务状态、返回任务编号…等

二、Jenkins Api 环境准备

创建一个有任务运行和查询权限的用户
较老版本的Jenkins操作关闭跨站脚本伪造请求保护,新版本的Jenkins无此选项了

1、获取所有job接口

curl -u USERNAME:PASSWORD “JENKINSURL:PORT/api/json?pretty=true”

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/api/json?pretty=true"

在这里插入图片描述

2、获取所有job名字接口

[root@mylinux1 ~]# curl -u admin:admin -g "http://192.168.22.3:8080/api/json?pretty=true&tree=jobs[name]"

{
  "_class" : "hudson.model.Hudson",
  "jobs" : [
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "build_no_params"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "build_with_params"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "father_job"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "first_job"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "git_demo"

3、获取所有job名字和url接口

[root@mylinux1 ~]# curl -u admin:admin -g "http://192.168.22.3:8080/api/json?pretty=true&tree=jobs[name,url]"

{
  "_class" : "hudson.model.Hudson",
  "jobs" : [
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "build_no_params",
      "url" : "http://192.168.22.3:8080/job/build_no_params/"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "build_with_params",
      "url" : "http://192.168.22.3:8080/job/build_with_params/"
    },
    {
      "_class" : "hudson.model.FreeStyleProject",
      "name" : "father_job",
      "url" : "http://192.168.22.3:8080/job/father_job/"
    },

三、使用curl调用 获取所有构建队列

curl -u USERNAME:PASSWORD JENKINSURL:PORT/queue/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/queue/api/json?pretty=true"
{
  "_class" : "hudson.model.Queue",
  "discoverableItems" : [
    
  ],
  "items" : [
    
  ]

四、使用curl调用 获取Job信息

获取任务所有信息
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/build_with_params/api/json?pretty=true" 

获取最后一次构建信息
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/lastBuild/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/build_with_params/lastBuild/api/json?pretty=true"

获取最后稳定构建信息
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/lastStableBuild/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/build_with_params/lastStableBuild/api/json?pretty=true"

获取最后成功的构建
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/lastSuccessfulBuild/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/build_with_params/lastSuccessfulBuild/api/json?pretty=true"

获取最后完成的构建
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/lastCompletedBuild/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/build_with_params/lastCompletedBuild/api/json?pretty=true"

最近失败的构建
curl -u USERNAME:PASSWORD JENKINSURL:PORT/job/JOBNAME/lastFailedBuild/api/json?pretty=true

[root@mylinux1 ~]# curl -u admin:admin "http://192.168.22.3:8080/job/maven_demo/lastFailedBuild/api/json?pretty=true"

五、使用curl调用操作Job

1、操作Job需要验证crumb

a、使用token发起接口(不推荐)

在这里插入图片描述

b、获取crumb使用

[root@mylinux1 ~]# username_password="admin:admin"
[root@mylinux1 ~]# jenkins_url="http://192.168.22.3:8080"
[root@mylinux1 ~]# cookie_file="$(mktemp)"
[root@mylinux1 ~]# jenkins_crumb=$(curl -s -f -u "${username_password}" --cookie-jar "${cookie_file}" -s "${jenkins_url}/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,%22:%22,//crumb)")
[root@mylinux1 ~]# echo $jenkins_crumb
Jenkins-Crumb:bcc9f0c335fbcffe6e12f5aa4398ec2bdc74749b72b3389003bdc3f321d9b164

c、上面命令操作完成后会生成config.xml文件

[root@mylinux1 ~]# ls config.xml
config.xml
vim config.xml

<?xml version='1.1' encoding='UTF-8'?>
<project>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties/>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>echo &quot;good&quot;</command>
      <configuredLocalRules/>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>

2、创建job

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/createItem?name=create_job2" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}" -H 'Content-Type:text/xml' --data-binary "@./config.xml"
[root@mylinux1 ~]# 

在这里插入图片描述

3、复制job

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/createItem?name=create_job3&mode=copy&from=create_job1" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}"
[root@mylinux1 ~]# 

在这里插入图片描述

4、修改job

在这里插入图片描述

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/create_job2/config.xml" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}" -H 'Content-Type:text/xml' --data-binary "@./config.xml"
[root@mylinux1 ~]# 

在这里插入图片描述

5、无参构建

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/build_no_params/build" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}"
[root@mylinux1 ~]# 

在这里插入图片描述

6、有参构建

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/build_with_params/buildWithParameters" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}" --data-urlencode json='{"env":"dev"}'

在这里插入图片描述

7、删除job

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/create_job2/doDelete" --cookie "${cookie_file}" -X POST -H "${jenkins_crumb}"

六、使用curl调用 操作指定构建的Job

查看最新构建任务编号
curl -u USERNAME:PASSWORD “JENKINSURL:PORT/job/son_demo/lastBuild/buildNumber”

查看某次构建控制台日志
curl -u USERNAME:PASSWORD “JENKINSURL:PORT/job/JOBNAME/ID/logText/progressiveText”

删除某次构建
curl -u USERNAME:PASSWORD "JENKINSURL:PORT/job/JOBNAME/ID/doDelete" -X POST --cookie "${cookie_file}" -H "${jenkins_crumb}"

1、查看最新构建任务编号

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/build_with_params/lastBuild/buildNumber"
5[root@mylinux1 ~]# 

在这里插入图片描述
在这里插入图片描述

2、查看某次构建控制台日志

[root@mylinux1 ~]# curl -u "${username_password}" "${jenkins_url}/job/build_with_params/6/logText/progressiveText"Started by user admin
Running as SYSTEM
Building on the built-in node in workspace /var/jenkins_home/workspace/build_with_params
[build_with_params] $ /bin/sh -xe /tmp/jenkins11717514708564825855.sh
+ [ online = dev ]
+ [ online = test ]
+ [ online = online ]
+ echo online runtime
online runtime
Finished: SUCCESS
[root@mylinux1 ~]# 

在这里插入图片描述
在这里插入图片描述

3、删除某次构建

在这里插入图片描述
在这里插入图片描述

七、Python Jenkins Api常用接口操作

1、安装 pip install jenkinsapi

2、jenkinsapi 连接Jenkins服务

from jenkinsapi import jenkins

class JenkinsApiStudy:

    def __init__(self):
        """
        实现对jenkins的连接
        """
        jenkins_url="http://192.168.22.3:8080"
        #username="admin"
        #password="admin"
        用户名="admin"
        密码="admin"
        self.my_jenkins = jenkins.Jenkins(jenkins_url, username, password, use_crumb=True)

3、jenkinsapi 获取所有jobs

    def get_all_jobs(self):
        """
        jenkinsapi 获取所有jobs
        :return:
        """
        jobs=[]
        # 需要注意,如果请求的url与Jenkins Location配置的Jenkins URL不一致时,获取到的key会拼接上一截地址
        #jobs=self.my_jenkins.keys()  # 获取所有的job名称
        for info in self.my_jenkins.get_jobs_info():
            jobs.append(info) # 获取job的url与名称  比较卡
        return jobs

4、jenkinsapi 获取构建队列

    def get_queue(self):
        """
        获取队列信息
        :return:
        """
        return self.my_jenkins.get_queue().keys()

5、jenkinsapi 获取Job信息

    def get_job_info(self,job_name):
        """
        jenkinsapi 获取Job信息
        :return:
        """
        # 获取job对象
        my_job=self.my_jenkins.get_job(job_name)
        # 获取最后一次构建对象
        print(my_job.get_last_build())
        # 获取最后一次完成的构建对象
        print(my_job.get_last_completed_build())
        # 获取最后一次成功的构建对象
        print(my_job.get_last_good_build())
        # 获取最后一次失败的构建编号
        print(my_job.get_last_failed_buildnumber())

6、jenkinsapi 操作Job信息

        def deal_job(self,job_name):
        """
        jenkinsapi 操作Job信息
        :param job_name: job名称
        :return:
        """
        #my_job = self.my_jenkins.get_job(job_name)
        # 获取job的config
        #print(my_job.get_config())
        # 创建job
        # 先获取到job的config
        with open(f"{job_name}_config.xml", "w", encoding="utf-8") as f:
            my = self.my_jenkins.get_job(job_name).get_config()
            f.write(my)
        self.my_jenkins.create_job("create_python_job", open("./build_no_params_config.xml", encoding="utf-8").read())
        # 复制job
        self.my_jenkins.copy_job(job_name, "build_no_params_job1")
        #todo 禁用job:当创建job或者复制job时,会出现job没有构建功能;操作:禁用后再操作启用
        #my_job.disable()
        # 启用job
        #my_job.enable()
        # 重命名job
        self.my_jenkins.rename_job(job_name, f"{job_name}_new")
        # 无参构建
        self.my_jenkins.build_job(job_name)
        # 有参构建
        self.my_jenkins.build_job(job_name, params={"env": "test"})
        # 删除job
        #self.my_jenkins.delete_job(job_name)

a、查看my_job.get_config()信息

在这里插入图片描述

b、查看生成的config.xml文件

 def deal_job(self,job_name):
        """
        jenkinsapi 操作Job信息
        :param job_name: job名称
        :return:
        """
        #my_job = self.my_jenkins.get_job(job_name)
        # 获取job的config
        #print(my_job.get_config())
        # 创建job
        # 先获取到job的config
        with open(f"{job_name}_config.xml", "w", encoding="utf-8") as f:
            my = self.my_jenkins.get_job(job_name).get_config()
            f.write(my)
        self.my_jenkins.create_job("create_python_job", open("./build_no_params_config.xml", encoding="utf-8").read())

在这里插入图片描述

7、jenkinsapi 操作指定构建的Job

    def get_build_info(self,job_name,build_id=None):
        """
        jenkinsapi 操作指定构建的Job 获取build信息
        :param job_name: job名称
        :param build_id: 构建id
        :return:
        """
        my_job = self.my_jenkins.get_job(job_name)
        # 当前job对象是否在队列/构建中
        print(my_job.is_queued_or_running())
        # 获取指定构建ID的对象
        build_object = my_job.get_build(build_id)
        # 获取构建对象的时间戳
        print(build_object.get_timestamp())
        # 获取控制台日志
        print(build_object.get_console())
        # 获取构建参数
        print(build_object.get_params())
        # 获取构建的状态
        print(build_object.get_status())
        # 获取构建的变更日志
        print(build_object.get_changeset_items())
        # 删除指定构建
        #my_job.delete_build(build_id)

输出结果

2023-04-16 05:52:26+00:00
Started by user admin
Running as SYSTEM
Building on the built-in node in workspace /var/jenkins_home/workspace/build_with_params
[build_with_params] $ /bin/sh -xe /tmp/jenkins12197874264732667620.sh
+ [ test = dev ]
+ [ test = test ]
+ echo test runtime
test runtime
Finished: SUCCESS

{'env': 'test'}
SUCCESS
[]

8、整合以上代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/16 21:47
# @Author  : 杜兰特
# @File    : jenkins_api_study.py

from jenkinsapi import jenkins

class JenkinsApiStudy:

    def __init__(self):
        """
        实现对jenkins的连接
        """
        jenkins_url="http://192.168.22.3:8080"
        #username="admin"
        #password="admin"
        用户名="admin"
        密码="admin"
        self.my_jenkins = jenkins.Jenkins(jenkins_url, username, password, use_crumb=True)

    def get_all_jobs(self):
        """
        jenkinsapi 获取所有jobs
        :return:
        """
        jobs=[]
        # 需要注意,如果请求的url与Jenkins Location配置的Jenkins URL不一致时,获取到的key会拼接上一截地址
        #jobs=self.my_jenkins.keys()  # 获取所有的job名称
        for info in self.my_jenkins.get_jobs_info():
            jobs.append(info) # 获取job的url与名称  比较卡
        return jobs

    def get_queue(self):
        """
        获取队列信息
        :return:
        """
        return self.my_jenkins.get_queue().keys()

    def get_job_info(self,job_name):
        """
        jenkinsapi 获取Job信息
        :return:
        """
        # 获取job对象
        my_job=self.my_jenkins.get_job(job_name)
        # 获取最后一次构建对象
        print(my_job.get_last_build())
        # 获取最后一次完成的构建对象
        print(my_job.get_last_completed_build())
        # 获取最后一次成功的构建对象
        print(my_job.get_last_good_build())
        # 获取最后一次失败的构建编号
        print(my_job.get_last_failed_buildnumber())

    def deal_job(self,job_name):
        """
        jenkinsapi 操作Job信息
        :param job_name: job名称
        :return:
        """
        my_job = self.my_jenkins.get_job(job_name)
        # 获取job的config
        print(my_job.get_config())
        # 创建job
        # 先获取到job的config
        # with open(f"{job_name}_config.xml", "w", encoding="utf-8") as f:
        #     my = self.my_jenkins.get_job(job_name).get_config()
        #     f.write(my)
        #self.my_jenkins.create_job("create_python_job", open("./build_no_params_config.xml", encoding="utf-8").read())
        # 复制job
        # self.my_jenkins.copy_job(job_name, "build_no_params_job1")
        #todo 禁用job:当创建job或者复制job时,会出现job没有构建功能;操作:禁用后再操作启用
        #my_job.disable()
        # # 启用job
        #my_job.enable()
        # 重命名job
        # self.my_jenkins.rename_job(job_name, f"{job_name}_new")
        # 无参构建
        # self.my_jenkins.build_job(job_name)
        # 有参构建
        # self.my_jenkins.build_job(job_name, params={"env": "test"})
        # # 删除job
        #self.my_jenkins.delete_job(job_name)


    def get_build_info(self,job_name,build_id=None):
        """
        jenkinsapi 操作指定构建的Job 获取build信息
        :param job_name: job名称
        :param build_id: 构建id
        :return:
        """
        my_job = self.my_jenkins.get_job(job_name)
        # 当前job对象是否在队列/构建中
        print(my_job.is_queued_or_running())
        # 获取指定构建ID的对象
        build_object = my_job.get_build(build_id)
        # 获取构建对象的时间戳
        print(build_object.get_timestamp())
        # 获取控制台日志
        print(build_object.get_console())
        # 获取构建参数
        print(build_object.get_params())
        # 获取构建的状态
        print(build_object.get_status())
        # 获取构建的变更日志
        print(build_object.get_changeset_items())
        # 删除指定构建
        #my_job.delete_build(build_id)



if __name__ == '__main__':
    jk=JenkinsApiStudy()
    #print(jk.get_all_jobs())
    #print(jk.get_queue())
    #jk.get_job_info("python_interface_project")
    #jk.deal_job("build_no_params")
    jk.get_build_info("build_with_params",10)
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐