使用jenkins-client批量修改job任务配置
添加依赖:
<dependency>
<groupId>com.offbytwo.jenkins</groupId>
<artifactId>jenkins-client</artifactId>
<version>0.3.8</version>
</dependency>
JenkinsConnect.java
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.model.Job;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class JenkinsConnect {
private JenkinsConnect() {
}
private static String jenkinsUrl = "http://xxx.xxx.xxx.xxx:xxxx/jenkins";
// 连接 Jenkins 需要设置的信息\
private static String jenkinsUsername = "xxxxx";
private static String jenkinsPassword = "xxxxx";
/**
* Http 客户端工具
* <p>
* 如果有些 API 该Jar工具包未提供,可以用此Http客户端操作远程接口,执行命令
*
* @return
*/
public static JenkinsHttpClient getClient() {
JenkinsHttpClient jenkinsHttpClient = null;
System.out.println(jenkinsUrl);
try {
jenkinsHttpClient = new JenkinsHttpClient(new URI(jenkinsUrl), jenkinsUsername, jenkinsPassword);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jenkinsHttpClient;
}
/**
* 连接 Jenkins
*/
public static JenkinsServer connection() {
JenkinsServer jenkinsServer = null;
try {
jenkinsServer = new JenkinsServer(new URI(jenkinsUrl), jenkinsUsername, jenkinsPassword);
} catch (URISyntaxException e) {
e.printStackTrace();
}
return jenkinsServer;
}
public static void main(String[] args) throws Exception {
String viewName = "sit-后端应用";
JenkinsHttpClient client = JenkinsConnect.getClient();
JenkinsServer jenkinsServer = JenkinsConnect.connection();
Map<String, Job> jobs = jenkinsServer.getJobs();
//遍历获取到所有的jobname
for (String jobname : jobs.keySet()) {
System.out.println("jobname = " + jobname);
String jobXml = jenkinsServer.getJobXml(jobname);
if (jobXml.contains("bash_profile") && !jobXml.contains("/etc/profile")) {
jobXml = jobXml.replaceFirst("bash_profile", "bash_profile \n source /etc/profile ");
System.out.println("job[" + jobname + "] add source /etc/profile success");
jenkinsServer.updateJob(jobname, jobXml);
}
}
// View view = jenkinsServer.getView(viewName);
jenkinsServer.getView()
// System.out.println("view = " + view);
// String viewXml = client.get("/view/" + viewName + "/api/xml");
// System.out.println("viewXml = " + viewXml);
}
}
参考
java调用JenkinsServer API操作_red_blue2的博客-CSDN博客_com.offbytwo.jenkins
?如何批量修改Jenkins job的配置?_weixin_34054866的博客-CSDN博客
|