用到的库:
"github.com/bndr/gojenkins"
代码如下,一次到位:
import (
"context"
"fmt"
"time"
"github.com/bndr/gojenkins"
)
// 构建指定任务
func buildJob(ctx context.Context, jenkins *gojenkins.Jenkins, name string) (n int64) {
var err error
n, err = jenkins.BuildJob(ctx, name, nil)
if err != nil {
panic(err)
}
fmt.Println("构建完成:", n) // n是序号
return
}
// 停止构建
// 从别处来源,进行停止(可能非最新,需要时间)
func stopBuildByJobLatest(ctx context.Context, jenkins *gojenkins.Jenkins, name string) {
job, err := jenkins.GetJob(ctx, name)
if err != nil {
panic(err)
}
lastBuild, err := job.GetLastBuild(ctx)
if err != nil {
return
}
number := lastBuild.Raw.ID
fmt.Println("准备停止:", number)
stopped, err := lastBuild.Stop(ctx)
if err != nil {
panic(err)
}
fmt.Println("是否停止:", stopped)
}
调用发起构建:
func main() {
ctx := context.Background()
jenkins, _ := gojenkins.CreateJenkins(nil, "http://192.168.30.116:18080", "用户名", "密码").Init(ctx)
// 构建helloworld
buildJob(ctx, jenkins, "helloworld")
}
效果:
如需要停止:
stopBuildByJobLatest( ctx, jenkins, "helloworld")