golang 操作Jenkins

1.創建Agent/Node

Go 复制代码
func CreateAgent(username string, password string, nodeName string, nodeDescription string, numExecutors string, remoteFS string, labelString string, host string) {

	var obj string

	obj = "{'name':+'" + nodeName + "',+'nodeDescription':+'" + nodeDescription + "',+'numExecutors':+'" + numExecutors + "',+'remoteFS':+'" + remoteFS + "',+'labelString':+'" + labelString + "',+'mode':+'NORMAL',+'':+['hudson.plugins.sshslaves.SSHLauncher',+'0'],+'launcher':+{'stapler-class':+'hudson.plugins.sshslaves.SSHLauncher',+'$class':+'hudson.plugins.sshslaves.SSHLauncher',+'host':+'" + host + "',+'includeUser':+'false',+'credentialsId':+'" + credentialsId + "',+'':+'0',+'sshHostKeyVerificationStrategy':+{'stapler-class':+'hudson.plugins.sshslaves.verifiers.KnownHostsFileKeyVerificationStrategy',+'$class':+'hudson.plugins.sshslaves.verifiers.KnownHostsFileKeyVerificationStrategy'},+'port':+'" + port + "',+'javaPath':+'',+'jvmOptions':+'',+'prefixStartSlaveCmd':+'',+'suffixStartSlaveCmd':+'',+'launchTimeoutSeconds':+'',+'maxNumRetries':+'',+'retryWaitTime':+'',+'tcpNoDelay':+true,+'workDir':+''},+'retentionStrategy':+{'stapler-class':+'hudson.slaves.RetentionStrategy$Always',+'$class':+'hudson.slaves.RetentionStrategy$Always'},+'nodeProperties':+{'stapler-class-bag':+'true'},+'type':+'hudson.slaves.DumbSlave',+'Submit':+''}"

	jenkinsUser := "Jenkins的用户"
	jenkinsAPIToken := "Jenkins的token"
	jsonObject := obj
	jenkinsURL := "http://127.1.1:80" //Jeknins地址
	data := fmt.Sprintf(`json=%s`, jsonObject)

	req, err := http.NewRequest("POST", jenkinsURL+"/computer/doCreateItem?name="+nodeName+"&type=hudson.slaves.DumbSlave", bytes.NewBufferString(data))
	if err != nil {
		Err("CreateAgent error : %v\n", err)
		return req.Response.StatusCode
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(jenkinsUser+":"+jenkinsAPIToken))))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		Err("CreateAgent error : %v\n", err)
		return resp.StatusCode
	}
	defer resp.Body.Close()
	 body, err := io.ReadAll(resp.Body)
	 if err != nil {
	 	fmt.Println("读取响应失败:", err)
	 	return
	 }
	 fmt.Println("响应内容:", string(body))
	 fmt.Println("\n\n响应状态码 ", resp.StatusCode)


}

nodeName 你创建的node的名字

nodeDescription 描述,空也可以

numExecutors 一般1

remoteFS 远程控制的目录,类似 home/Aaron

labelString 不写也可以

host 远程主机的host

credentialsId 凭证,用来连接到远程主机的

2.创建凭证

Go 复制代码
func  CreateCredentials(username string, password string, id string)  {
	var obj string

	obj = "{'':+'0',+'credentials':+{'scope':+'GLOBAL',+'username':+'" + username + "',+'usernameSecret':+false,+'password':+'" + password + "',+'$redact':+'password',+'id':+'" + id + "',+'description':+'',+'stapler-class':+'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl',+'$class':+'com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl'},+'Submit':+''}"

	jenkinsUser := "Jenkins的用户"
	jenkinsAPIToken := "Jenkins的token"
	jsonObject := obj
	jenkinsURL := "http://127.1.1:80" //Jeknins地址
	data := fmt.Sprintf(`json=%s`, jsonObject)

	req, err := http.NewRequest("POST", jenkinsURL+"/manage/credentials/store/system/domain/_/createCredentials", bytes.NewBufferString(data))
	if err != nil {
		Err("CreateCredentials error : %v\n", err)
		return 
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(jenkinsUser+":"+jenkinsAPIToken))))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		Err("CreateCredentials error : %v\n", err)
		return 
	}
	defer resp.Body.Close()

}

username 创建凭证的用户名

password 创建凭证的密码

id 凭证的id,唯一,创建node的时候会用到

3.创建Job

Go 复制代码
func  CreateJob(jobName string, agent string, command string)  {
	jenkinsURL := "http://127.1.1:80" //Jeknins地址

	url := jenkinsURL + "/createItem?name=" + jobName

	data := `<project>
				<actions/>
				<description></description>
				<keepDependencies>false</keepDependencies>
				<properties/>
				<scm class="hudson.scm.NullSCM"/>
				<assignedNode>` + agent + `</assignedNode>
				<canRoam>false</canRoam>
				<disabled>false</disabled>
				<blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
				<blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
				<triggers/>
				<concurrentBuild>false</concurrentBuild>
				<builders>
				<hudson.tasks.Shell>
					<command>` + command + `
					</command>
					<configuredLocalRules/>
				</hudson.tasks.Shell>
				</builders>
				<publishers/>
				<buildWrappers>
				<hudson.plugins.timestamper.TimestamperBuildWrapper plugin="timestamper@1.25"/>
				</buildWrappers>
				</project>`



	jenkinsUser := "Jenkins的用户"
	jenkinsAPIToken := "Jenkins的token"

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(data)))
	if err != nil {
		Err("Error creating request:", err)
		return req.Response.StatusCode
	}

	req.Header.Set("Content-Type", "application/xml")
	req.SetBasicAuth(jenkinsUser, jenkinsAPIToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}
	defer resp.Body.Close()
}

jobName 你创建的Job的名字

agent 你的Job要跑在那个agent/node上面

command 执行的命令,类似 "ls pwd"等

4.执行Job

Go 复制代码
func  BuildNow(jobName string)  {
	jenkinsURL := "http://127.1.1:80" //Jeknins地址

	url := jenkinsURL + "/job/" + jobName + "/build?delay=0sec"

	jenkinsUser := "Jenkins的用户"
	jenkinsAPIToken := "Jenkins的token"

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte("")))
	if err != nil {
		return
	}

	req.Header.Set("Content-Type", "application/xml")
	req.SetBasicAuth(jenkinsUser, jenkinsAPIToken)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

}

5.获取Job信息

Go 复制代码
url := fmt.Sprintf("http://%s@%s:%d/%s/api/json", Token, Addr, Port, api)

url = fmt.Sprintf("%s?depth=%d", url, 2)

		req, err := http.NewRequest("GET", url, bytes.NewBuffer([]byte("")))

Token jenkins的token

Addr jenkins地址

Port jenkins端口号

api 固定写"computer"

这边会返回很多信息,都是json信息,然后你可以自己分析其中的内容。

PS:

这些API 你都可以自己去找,打开Jenkins,打开浏览器开发选项(选择network),然后做你要做的时候,就可以找到对应的API的动作了。Reuqest URL就是 API的地址,往下拉可以看到请求的内容。

相关推荐
虫小宝12 分钟前
淘客系统的容灾演练与恢复:Java Chaos Monkey模拟节点故障下的服务降级与快速切换实践
java·开发语言
zz345729811313 分钟前
c语言基础概念9
c语言·开发语言
yxm263366908114 分钟前
【洛谷压缩技术续集题解】
java·开发语言·算法
键盘帽子15 分钟前
多线程情况下长连接中的session并发问题
java·开发语言·spring boot·spring·spring cloud
毅炼22 分钟前
Java 基础常见问题总结(1)
开发语言·python
fengxin_rou31 分钟前
【黑马点评实战篇|第一篇:基于Redis实现登录】
java·开发语言·数据库·redis·缓存
数智工坊41 分钟前
【数据结构-栈】3.1栈的顺序存储-链式存储
java·开发语言·数据结构
R-G-B1 小时前
python 验证每次操作图片处理的顺序是否一致,按序号打上标签,图片重命名
开发语言·python·图片重命名·按序号打上标签·验证图片处理的顺序
小二·1 小时前
Go 语言系统编程与云原生开发实战(第10篇)性能调优实战:Profiling × 内存优化 × 高并发压测(万级 QPS 实录)
开发语言·云原生·golang
多多*1 小时前
2月3日面试题整理 字节跳动后端开发相关
android·java·开发语言·网络·jvm·adb·c#