如何批量修改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的配置");
 }

  

posted on 2018-01-31 12:05  朱古力88  阅读(6115)  评论(0编辑  收藏  举报