如何批量修改Jenkins job的配置?

背景:jerkins 有100多个job,但是运行机器下线了,需要修改所有job的机器配置,手工一条条修改的话会疯掉的,所以想到写一个脚本进行批量修改。

思路:第一步:获取Jenkins的所有jobname

         第二步:  遍历jobname,获取每个job的配置文件config.xml

         第三步:将获取到的xml类型字符串转化为document对象,然后修改机器节点的值,然后将修改的document对象写入一个新的xml文件

         第四步:将新的修改后的xml文件作为参数传给job

好了,上代码:

import org.xml.sax.InputSource;
import com.offbytwo.jenkins.JenkinsServer;
import java.net.URI;

import org.jdom2.input.SAXBuilder;
import org.jdom2.Document;
import org.jdom2.Element;


public void modifyJenkinsTest(){
        String username=*******;
        String password=*******;
        String url = *******;
        String filename="tempConfig.xml";
        //count 用于统计成功修改多少个job的配置
        int count=0;
        try {
            JenkinsServer jenkins = new JenkinsServer(new URI(url), username, password);
            Map<String, Job> jobs = jenkins.getJobs();
            //遍历获取到所有的jobname
            for (String jobname:jobs.keySet()) {                 
                String configUrl = url+"job/" + jobname + "/config.xml"; 
                //在这里需要单独写一个httpRequest类,里面写一个静态函数sendGet,需要携带Authorization参数,因为访问Jenkins需要认证信息,(通过用户名和密码生成)
                String response = httpRequest.sendGet(configUrl, "");  
                # 将字符串xml转化为document对象
                StringReader read = new StringReader(response); 
                InputSource source = new InputSource(read);      
                SAXBuilder sb = new SAXBuilder();
                Document document; 
                document = sb.build(source); 
                Element root = document.getRootElement(); 
                //配置文件没有assignedNode节点或者这个节点的值已经修改过了就跳过这条job 

                if(root.getChild("assignedNode")==null||root.getChild("assignedNode").getText().equals("********")){ 
                    continue; 
                } 
                //修改document对象中名字为assignedNode的节点的值为*******
                root.getChild("assignedNode").setText("********"); 
                //将修改之后的xml对象写入一个临时的xml文件
                File file = new File(filename); 
                XMLOutputter outputter = new XMLOutputter(format); 
                outputter.output(document, new FileOutputStream(file)); 
                //将修改之后xml文件传给job,进行修改
                //在这里需要单独写一个httpRequest类,里面写一个静态函数requestPost,需要携带Authorization参数,因为访问Jenkins需要认证信息,(通过用户名和密码生成)
                httpRequest.requestPost(configUrl, filename); 
                //修改成功一个,count加1
                count++; 
            } 
        }catch (Exception e){ 
            e.printStackTrace();
        } 
        System.out.println("成功修改了"+count+"条job的配置");
 }

  

转载于:https://www.cnblogs.com/zhaijing/p/8391558.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值