Go操作Jenkins

Jenkins是最受欢迎的开源持续集成系统,在我们的工作当中,经常用到。这里介绍Go语言的第三方库gojenkins来调用Jenkins API实现对Jenkins的相关操作。

环境准备

需要有一个Jenkins环境,可以使用下面的命令快速运行一个Jenkins

1docker run --name jenkins -d -p 8080:8080 jenkins/jenkins:lts

启动完打开http://localhost:8080进行设置,这里假定你对Jenkins已经很了解了。

gojenkins特性

  • Get information on test-results of completed/failed build
  • Ability to query Nodes, and manipulate them. Start, Stop, set Offline.
  • Ability to query Jobs, and manipulate them.
  • Get Plugins, Builds, Artifacts, Fingerprints
  • Validate Fingerprints of Artifacts
  • Get Current Queue, Cancel Tasks
  • etc. For all methods go to GoDoc Reference.

安装gojenkins

1go get -u github.com/bndr/gojenkins

基本使用

连接jenkins

 1package main
 2
 3import (
 4	"github.com/bndr/gojenkins"
 5	"log"
 6)
 7
 8func main() {
 9	jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
10	// Provide CA certificate if server is using self-signed certificate
11	// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
12	// jenkins.Requester.CACert = caCert
13	_, err := jenkins.Init()
14
15	if err != nil {
16		log.Printf("连接Jenkins失败, %v\n",err)
17		return
18	}
19	log.Println("Jenkins连接成功")
20}

输出结果

12020/03/18 10:34:42 Jenkins连接成功

检测节点状态

 1package main
 2
 3import (
 4	"github.com/bndr/gojenkins"
 5	"log"
 6)
 7
 8func main() {
 9	jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
10	// Provide CA certificate if server is using self-signed certificate
11	// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
12	// jenkins.Requester.CACert = caCert
13	_, err := jenkins.Init()
14
15	if err != nil {
16		log.Printf("连接Jenkins失败, %v\n",err)
17		return
18	}
19	log.Println("Jenkins连接成功")
20
21	nodes, _ := jenkins.GetAllNodes()
22
23	for _, node := range nodes {
24
25		// Fetch Node Data
26		node.Poll()
27		if ok ,_ := node.IsOnline(); ok {
28			nodeName := node.GetName()
29			log.Printf("Node %s is Online\n", nodeName)
30		}
31	}
32}

输出结果

12020/03/18 10:40:59 Jenkins连接成功
22020/03/18 10:41:00 Node master is Online

获取任务状态

 1package main
 2
 3import (
 4	"github.com/bndr/gojenkins"
 5	"log"
 6)
 7
 8func main() {
 9	jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
10	// Provide CA certificate if server is using self-signed certificate
11	// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
12	// jenkins.Requester.CACert = caCert
13	_, err := jenkins.Init()
14
15	if err != nil {
16		log.Printf("连接Jenkins失败, %v\n",err)
17		return
18	}
19	log.Println("Jenkins连接成功")
20
21	_, err = jenkins.GetJob("job_name")
22	if err != nil {
23		panic("Job Does Not Exist")
24	}
25}

输出结果

12020/03/18 10:42:43 Jenkins连接成功
2panic: Job Does Not Exist
3
4goroutine 1 [running]:
5main.main()
6        /Users/jerry/go/src/jenkins/main.go:23 +0x1ca
7exit status 2

新建任务

 1package main
 2
 3import (
 4	"github.com/bndr/gojenkins"
 5	"log"
 6)
 7
 8func main() {
 9	jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
10	// Provide CA certificate if server is using self-signed certificate
11	// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
12	// jenkins.Requester.CACert = caCert
13	_, err := jenkins.Init()
14
15	if err != nil {
16		log.Printf("连接Jenkins失败, %v\n",err)
17		return
18	}
19	log.Println("Jenkins连接成功")
20
21	configString := `<?xml version='1.1' encoding='UTF-8'?>
22	<flow-definition plugin="workflow-job@2.37">
23	<actions/>
24	<description></description>
25	<keepDependencies>false</keepDependencies>
26	<properties/>
27	<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.80">
28	<script>node {
29
30		stage(&apos;Checkout&apos;) {
31		echo &apos;Checkout&apos;
32		//checkout scm
33		checkout([$class: &apos;GitSCM&apos;, branches: [[name: &apos;*/master&apos;]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: &apos;https://github.com/hzde0128/hblog&apos;]]])
34	}
35	}</script>
36	<sandbox>true</sandbox>
37	</definition>
38	<triggers/>
39	<disabled>false</disabled>
40	</flow-definition>`
41
42	_, err = jenkins.CreateJob(configString, "hblog")
43	if err != nil {
44		log.Printf("创建任务失败, 错误信息:%v\n", err)
45		return
46	}
47  log.Println("创建任务成功")
48}

输出结果

12020/03/18 11:10:24 Jenkins连接成功
22020/03/18 11:10:25 创建任务成功

获取任务执行时间

这个库没有看到触发构建的API,需要手动进行构建,获取任务构建的执行时间

 1package main
 2
 3import (
 4	"github.com/bndr/gojenkins"
 5	"log"
 6)
 7
 8func main() {
 9	jenkins := gojenkins.CreateJenkins(nil, "http://localhost:8080/", "admin", "admin")
10	// Provide CA certificate if server is using self-signed certificate
11	// caCert, _ := ioutil.ReadFile("/tmp/ca.crt")
12	// jenkins.Requester.CACert = caCert
13	_, err := jenkins.Init()
14
15	if err != nil {
16		log.Printf("连接Jenkins失败, %v\n",err)
17		return
18	}
19	log.Println("Jenkins连接成功")
20
21	build, err := jenkins.GetJob("hblog")
22	if err != nil {
23		panic("Job Does Not Exist")
24	}
25
26	lastSuccessBuild, err := build.GetLastSuccessfulBuild()
27	if err != nil {
28		panic("Last SuccessBuild does not exist")
29	}
30
31	// 默认单位是毫秒
32	duration := lastSuccessBuild.GetDuration()
33	dur := duration / 1000
34	log.Printf("构建持续时间:%v秒\n",dur)
35}

输出结果

12020/03/18 11:21:15 Jenkins连接成功
22020/03/18 11:21:15 构建持续时间:4秒

获取队列信息及原因

1tasks := jenkins.GetQueue()
2
3for _, task := range tasks {
4	fmt.Println(task.GetWhy())
5}

新建视图并添加任务到视图中

 1view, err := jenkins.CreateView("test_view", gojenkins.LIST_VIEW)
 2
 3if err != nil {
 4  panic(err)
 5}
 6
 7status, err := view.AddJob("jobName")
 8
 9if status != nil {
10  fmt.Println("Job has been added to view")
11}

其它高级用法

更多的功能还是参考GitHub上的库或者上go.dev去查找。